You are on page 1of 51

LP TRNH JAVA

Bi 8: Gii thiu v Swing

im danh

Nhc li bi trc
Khi nim Applets
S khc nhau gia Applets v Applications
Vng i ca applet
Mt s phng thc ca class Graphics
To mt applet
S dng tham s trong Applets
X l s kin
Mt s interface v class x l s kin
Mt s v d

Ni dung bi hc
Java Foundation Classes (AFC)
Abstract Windowing Toolkit (AWT)
Swing
Cc thng cha -Containers
Cc hp thoi - Dialogs
Qun l Layout
Cc thnh phn GUI Components
X l s kin

Java Foundation Classes (JFC)


FC (Foundation Classes) l mt nhm cc th vin

c thit k h tr lp trnh vin to ra cc


ng dng GUI trn Java.
FC n gin ha qu trnh thit k v lm gim

thi gian thc hin vit m.


Swing ch l mt trong nm th vin to nn JFC.

JFC cng cha Abstract Window Toolkit


(AWT),Accessibility API, 2D API v tng cng h
tr kh nng ko th (Drag and Drog).

Java Foundation Classes

AWT

Java 2D

Swing

JFC

Drag & Drop

Accessibility

Abstract Windowing Toolkit (AWT)


AWT cha nhiu class v
method cho php thit
k, qun l ca s v
font ch trn giao din
ha.

Mc ch chnh ca awt l
h tr cho cc ng dng
applet nhng cng c
dng thit k cc
chng trnh c giao din
ha c lp.

Tuy nhin AWT c hn ch:


Cc thnh phn GUI c th c hnh dng/hnh ng khc
nhau trn cc h iu hnh khc nhau (heavyweight)
Look and Feel ca mi thnh phn khng th (d dng) thay i.

Swing
Swing gii quyt cc hn ch lin quan n cc thnh phn

ca AWT thng qua vic s dng 2 tnh nng: cc thnh phn


lightweight v pluggable look and feel.

Cc thnh phn trong swing l lightweight: Cc thnh phn

ny c vit hon ton bng Java, do n khng ph


thuc vo mt h iu hnh c th no v n cng rt hiu
qu v linh hot.

Cc class Swing c kh nng vit nhng cm quan

(Look&Feels) cho mi thnh phn, v c th thay i cm


quan vo thi im chy.

Swing c rt nhiu nhng thnh phn mi nh table, tree,

slider, spinner, progress bar, internal frame v text.

Cc thnh phn ca Swing


Object
ButtonGroup

Component

ProgressMonitor

InputStream
FilterInputStream

Container
JComponent

JComboBox
AbstractButton

JButton

JCheckBox

JList
JLabel

JToggleButton

ProgressMonitorInputStream

JMenuItem

JRadioButton

JSlider
JScrollBar
JEditPane

JTextComponent

JTextArea

JPassword

JTextField

Containers
Mt container l mt thnh phn c bit c th cha
cc thnh phn khc.

Top-level container l mt container cp cao nht,


trn cng ca mt h thng phn cp.
Swing cung cp 4 container top-level container l:
JFrame, JDialog, JWindow v JApplet.
hin th trn mn hnh, mi mt thnh phn GUI
phi l mt phn ca h thng phn cp. Mi h
thng phn cp s c mt top-level l gc. Trong
JFrame hay c s dng nht.

Top-Level Containers

Menu Bar
Top-level
container

Cc thnh phn
c th nhn thy
(Visible)
Content
pane

JFrame
JFrame L top-level container.
JFrame c dng to ra 1 ca s.

JFrame()
JFrame(String title)

Cc thnh phn khc s c add vo

ca s JFrame :

frame.getContentPane().add(b); //c
frame.add(b)
//mi

JFrame
ng JFrame
public int getDefaultCloseOperation()

public void setDefaultCloseOperation(int operation)

Cc hng s khi ng 1 JFrame:

DISPOSE_ON_CLOSE ( value =1)


DO_NOTHING_ON_CLOSE (value = 2)
EXIT_ON_CLOSE (value = 3)
HIDE_ON_CLOSE (value = 4) // mc nh

JFrame
Khi thm cc thnh phn vo JFrame th:

Cc thnh phn c add vo content pane ca


Frame.

Content pane s dng BorderLayout lm mc nh.

S dng setSize() hoc pack() t kch thc ca s.

S dng show() hoc setVisible() hin th Frame.

JFrame
import javax.swing.*;
class FrameTest {

public static void main(String args[] {


JFrame frame = new JFrame(My Frame);//tiu
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,200);// t kch thc ca s
frame.show();// hoc setVisible(true)
}

JPanel
JPanel l container c dng nhm cc

thnh phn vi nhau.


JPanel s dng FlowLayout l mc nh.
JPanel c cc constructor:

JPanel()

JPanel(LayoutManager mg)

JPanel
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class Main {
public static void main(String args []) {
JFrame frame = new JFrame("JFrame is me");
JPanel jpan = new JPanel();
frame.add( jpan );
JButton btnHello = new JButton("Hello");
jpan.add(btnHello);
frame.setSize(300,100);
frame.setVisible(true);
}
}

JApplet
JApplet l mt container.
javax.swing.JApplet khc vi java.applet.Applet.
Khi thm cc thnh phn vo JApplet bt buc

phi thm vo content pane ca JApplet.

V d: getContentPane().add(component);

JApplet
import java.awt.*;
import javax.swing.*;
public class JAppletExample extends JApplet {
@Override
public void init() {
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
content.add(new JButton("Button 1"));
content.add(new JButton("Button 2"));
content.add(new JButton("Button 3"));
}
}

Dialog: JOptionPane
JOptionPane cho php bn d dng to ra cc hp thoi
nhp d liu v hin th kt qu. C rt nhiu la chn khi s
dng JOptionPane. Sau y l c php dng n gin:
Gi tr
userInput =

Phng thc
JOptionPane.showInputDialog(component, text);
JOptionPane.showMessageDialog(component, text);

Trong :
- component l ca s m hp thoi ny s t ln trn,
nu khng c th t l null
- text l xu k t

Dialog: JOptionPane
import javax.swing.JOptionPane;
public class JOptionPaneTest1 {
public static void main(String[] args) {
String ans;
ans = JOptionPane.showInputDialog(null, "Tc trn gi?");
double mph = Double.parseDouble(ans);
double kph = 1.621 * mph;
JOptionPane.showMessageDialog(null, "KPH = " + kph);
System.exit(0);
}
}

Dialog: JFileChooser
S dngJFileChooser dng la chn mt tp tin hoc
th mc trong a.
JFileChooser fileChooser = new JFileChooser();

int retval = fc.showOpenDialog(null);

if (retval == JFileChooser.APPROVE_OPTION) {
File myFile = fc.getSelectedFile();

//Cc thao tc x l file

Cho php chn file/th mc hoc c hai:


fc.setFileSelectionMode(JFileChooser.FILES_ONLY);//mc nh
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

Layout
FlowLayout
GridLayout

Object

BorderLayout
GridBagLayout
BoxLayout
CardLayot

FlowLayout
L Layout n gin v l mc nh cho Panel.
Cc thnh phn c sp xp theo hng.
Hng ca layout:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
Khong cch gia cc thnh phn:

C gi tr mc nh = 5

C th t li qua phng thc setHgap v setVgap.

GridLayout
L tp hp cc li c
cng kch thc
Khong cch gia cc :
Mc nh = 5
C th t li qua phng thc setHgap v setVgap.
Thay i kch thc ca cc :
Cc c th c kch thc to hn ph thuc vo
kch thc ca ca s.

BorderLayout
C 5 vng:
NORTH, SOUTH, EAST, WEST, CENTER
Khng phi tt c 5 vng u c s dng
t cc thnh phn vo mt v tr:
Panel.setLayout(new BorderLayout())
Panel.add(new JButton(Click here),
BorderLayout.NORTH)
t li khong cch gia cc thnh phn:
C th t li qua phng thc setHgap v setVgap.
S dng BorderLayout(int horGap, int verGap)

BoxLayout

Cc thnh phn c sp xp:


X_AXIS: Theo chiu ngang t tri qua phi
Y_AXIS: Theo chiu dc t trn xung di
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

BoxLayout
Y Axis

X Axis

Components
Mt s component thng dng:
JApplet**
JButton
JCheckBox
JColorChooser
JComboBox
JDialog**
JFileChooser
JFormattedTextField
JFrame**
JLabel

JMenu
JList
JMenuBar
JMenuItem
JPopupMenu
JPanel
JProgressBar
PasswordField
JRadioButton
ScrollBar

JSlider
JSpinner
JTable
JTextArea
JTextField
JToggleButton
JToolBa
JTree
JWindow **

**: L top-level containers.

Component: JLabel
JPanel textPanel = new JPanel();
JLabel redLabel = new JLabel("Red");
redLabel.setLocation(0, 0);
redLabel.setSize(50, 40);
textPanel.add(redLabel);

textPanel

Component: JButton
Khi to:
String text;
Icon image;
JButton btn = new JButton(text)
JButton btn = new JButton(text,image)
JButton btn = new JButton(image)

Phng thc:
ActionListener listener;
boolean b;
btn.addActionListener(listener);
btn.setEnable(b);

Component: JButton
X l s kin vi JButton:
Khi mt button c click th phng thc
actionPerformed()c thc hin vi mt ActionEvent
c truyn vo.
V d:
JButton btn = new JButton(Do Something);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
doMyAction();// khi click vo button
}
}
);

Component: JTextField
Cc phng thc:
JTextField txt = new JTextField(20) ;
txt.setText(Enter here);
Hoc JTextField txt= new JTextField("Enter here",
String str=txt.getText();

20);

txt.addActionListener(listener);
txt.setEditable(true/false);
txt.setFont(font);
txt.setHorizontalAlignment(align);
txt.requestFocus();//t con tr vo textbox

Component: JTextField
public class textFieldUpperCase extends JFrame {
public textFieldUpperCase() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField text = new JTextField(40);
text.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
text.setText(text.getText().toUpperCase());
}
});
getContentPane().add(text, BorderLayout.NORTH);
pack(); setVisible(true);
}
public static void main(String[] args) {
new textFieldUpperCase();
}
}

Component: JCheckBox
JCheckBox cb; //mt checkbox
String text;
//mt gi tr text
boolean state; //Gi tr true hoc false
cb = new JCheckBox(text); hoc
cb = new JCheckBox(text,state);
state = cb.isSelected();
cb.setSelected(state);
cb.addActionListener(listener);
cb.addItemListener(itemListener);

Component: JCheckBox
X l s kin khi click vo Checkbox:

ActionListener listener = new ActionListener(){

public void actionPerformed(ActionEvent event)


{

int mode = 0;

if (bold.isSelected()) mode += Font.BOLD;

if (italic.isSelected()) mode += Font.ITALIC;

label.setFont(new Font("Serif", mode, FONTSIZE));

};

bold.addActionListener(listener);

italic.addActionListener(listener);

Component: JRadio
JRadioButton yesButton
= new JRadioButton("Yes" , true);
JRadioButton noButton
= new JRadioButton("No" , false);
JRadioButton maybeButton = new JRadioButton("Maybe", false);
ButtonGroup bgroup = new ButtonGroup();
bgroup.add(yesButton);
bgroup.add(noButton);
bgroup.add(maybeButton);
JPanel radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(3, 1));
radioPanel.add(yesButton);
radioPanel.add(noButton);
radioPanel.add(maybeButton);

radioPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Married?"));

Component: JRadio
boolean b;
JRadioButton rb = new JRadioButton("Sample", false);

Mt s phng thc hay dng:


rb.isSelected();

Tr v true nu nt radio c chn.

rb.setSelected(b);

t nt radio l b (true/false).

rb.addActionListener(listener);

Thm vo hnh ng listener cho nt radio.


Nu radio ny c chn th listener s hot
ng.

Thm vo hnh ng listener cho nt radio.


rb.addItemListener(itemlistener); Nu radio ny c chn hoc b chn th
listener s hot ng.

Component: JList
C php:

JList()
JList(ListModel dataModel)
Jlist(Object[] listData)

Component: JList
V d:

JList boxes;

String names[] = {"Red", "Blue", "Green", "Orange", "Yellow",


Pink", "Cyan", "Gray", "Black", "Magenta"};
boxes = new JList(names);
boxes.setVisibleRowCount(10);

Component: JList
JList list;
DefaultListModel model;
int count = 5;
model = new DefaultListModel();
list = new JList(model);
JButton addButton = new JButton("Add Element");
for (int i = 0; i < 10; i++)
model.addElement("Element " + i);
addButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
model.addElement("Element " + counter);
counter++;
}
});

Component: JComboBox
Khi to:
String[] dias = {"lunes", "martes", "miercoles"};
JComboBox dayChoice = new JComboBox(dias)

Gi s c:
int index;
String item;
String obj; // obj c th kiu khc

Cc phng thc:
String JComboBox cb = new JComboBox(...);
cb.addActionListener(listener);

Component: JComboBox
Phng thc

ngha

cb.setSelectedIndex(index)

t mc c ch s l index c chn.

cb.setSelectedItem(obj)

t mc obj c chn.

cb.add(item)

Thm vo mt item.

cb.insert(item,index)

Thm vo item sau v tr index.

cb.remove(item)

Xa mc item khi combo box.

cb.remove(index)

Xa mc c ch s index ra khi
combo box.

index = cb.getSelectedIndex(); Tr v ch s ca mc c chn.


obj = cb.getSelectedItem(); Tr v gi tr ca mc ang c chn.

X l s kin
Mt s kin thng xy ra khi c s thay i trong giao

din ngi dng ha. V d nh khi ngi dng click


chut vo mt button, click vo mt mc trong combo
box v nh vy mt s kin s c kch hot.
Cc thnh phn ha (components) to ra cc s kin

ny c gi l ngun s kin (event source). Cc ngun


s kin s gi i mt i tng s kin (event object).
Cc s kin c x l bi mt s kin lng nghe (event

listener) c gn cho ngun s kin. Cc thnh phn


khc nhau ca GUI s c cc event listener khc nhau.

X l s kin
GUI
S kin
tc ng

Programspecific Action
handlers

ng k
Listener

Listeners
X l
s kin.

Xy dng GUI v kt ni (cn gi l ng k) ti cc listeners.


Listener s thc thi (implements) cc interface thch hp vi
tng loi s kin.
Thc hin cc lnh (trong x l s kin) ph hp vi ngun s kin.

X l s kin
Event Object

ActionEvent

Interface v method

interface ActionListener

Cc method lin kt

addActionListener

actionPerformed(ActionEvent) removeActionListener

Event Source

JButton
JCheckBox
JComboBox
JTextField
JRadioButton

ItemEvent

interface ItemListener

addItemListener

itemStateChanged(ItemEvent) removeItemListener

JCheckBox
JRadioButton
JComboBox

MouseEvent

interface MouseListener

addMouseListener

mousePressed(MouseEvent)

removeMouseListener Mouse ca bt k thnh

mouseReleased(MouseEvent)
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mouseClicked(MouseEvent)

c to bi s kin
phn GUI no.

X l s kin
S dng Inner Class Listener c tn: L cch

thng dng vit cc chng trnh nh.


Nhiu component c th dng chung Inner
Class ny.

Anonymous Inner Class Listeners: L inner class

khng t tn, thng c dng cho mt


component. Class dng ny khng c linh
hot.

Top-level Listeners (this): Thng c s dng

khi c mt event source.

X l s kin
import javax.swing.*;
import java.awt.event.*;
class SomePanel extends JPanel {
private JButton myGreetingButton = new JButton("Hello");
private JTextField myGreetingField = new JTextField(20);
public SomePanel() {
ActionListener doGreeting = new GreetingListener();
myGreetingButton.addActionListener(doGreeting);
myGreetingField.addActionListener(doGreeting);
// Cc lnh khc
}
// Inner class tn l GreetingListener
private class GreetingListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
myGreetingField.setText("Guten Tag");
}
}
}

X l s kin
class myPanel extends JPanel {
. . .
public MyPanel() {
JButton b1 = new JButton("Hello");

...
}

b1.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
// Cc lnh x l s kin cho b1
}
}
);

X l s kin
...
class Hello extends JApplet implements ActionListener{
JButton b;
...
public void init() {
JButton b = new JButton("Hello");
b.addActionListener(this);
...
}
public void actionPerformed(ActionEvent e) {
message = "Hi";
repaint();
}
...
}

Tng kt bi hc
Java Foundation Class (AFC)
Abstract Windowing Toolkit (AWT)
Swing
Cc thng cha -Containers
Cc hp thoi - Dialogs
Qun l Layout
Cc thnh phn GUI Components
X l s kin

You might also like