You are on page 1of 66

Lp trnh Java c bn

Cao c Thng - Trn Minh Tun cdthong@ifi.edu.vn, tmtuan@ifi.edu.vn

Bi 3. Cc thnh phn GUI


Mt v d n gin M hnh x l s kin Cc thnh phn GUI c bn S kin chut S kin bn phm B qun l trnh by (layout) Bi tp

V d: Applet tnh tng 2 s


// file TinhTong.java import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class TinhTong extends Applet implements ActionListener { private TextField txtNum1, txtNum2; private Button button; // phuong thuc nay duoc goi khi applet khoi tao public void init() { txtNum1 = new TextField(8); // tao o nhap so 1 txtNum2 = new TextField(8); // tao o nhap so 2 button = new Button("Tinh Tong"); // tao nut an
3

V d: Applet tnh tng 2 s


// dua cac thanh phan vao applet Demo add(txtNum1); add(txtNum2); add(button);

// khoi tao gia tri cho o nhap txtNum1.setText("0"); txtNum2.setText("0"); // dat nghe su kien bam nut button.addActionListener(this);

};

// phuong thuc nay duoc goi khi co mot hanh dong xay ra public void actionPerformed(ActionEvent event) { repaint(); }
4

V d: Applet tnh tng 2 s


Demo // phuong thuc nay duoc goi khi ve lai cua so
public void paint(Graphics g) { int num1, num2, sum; String s1 = txtNum1.getText(); num1 = Integer.parseInt(s1); String s2 = txtNum2.getText(); num2 = Integer.parseInt(s2); sum = num1 + num2; g.drawString("Tong cua hai so la: "+sum, 35, 80); }

V d: Applet tnh tng 2 s


Gii thch applet
TextField v Button l cc lp thuc gi java.awt ActionListener v ActionEvent l cc lp thuc gi java.awt.event TinhTong cn ci t giao din ActionListener v n s trc tip x l s kin n nt button.addActionListener(this); C th dng mt lp khc nghe s kin thay cho lp TinhTong
6

M hnh x l s kin
S kin (event) c pht sinh khi ngi dng tng tc vi GUI, v d: di chuyn chut, n nt, nhp d liu vn bn, chn menu... Thng tin v s kin c lu trong mt i tng thuc lp con ca lp AWTEvent (gi java.awt.event). Chng trnh c th x l cc s kin bng cch t lng nghe s kin trn cc thnh phn GUI.
7

M hnh x l s kin
Ba thnh phn chnh ca m hnh
Event source: ngun gy ra s kin, thng l cc thnh phn GUI trong chng trnh Event object: i tng lu thng tin v s kin xy ra Event listener: i tng s nhn c thng tin khi c s kin xy ra
Event source lu mt danh sch cc Event listener v s thng bo cho chng bit mi khi c s kin xy ra
8

M hnh x l s kin
V d:
Ngi dng n mt nt To thng tin v s kin Component Thng bo c s kin xy ra EventListener EventListener EventObject

Vic thng bo s kin xy ra thc cht l vic gi mt phng thc ca EventListener vi i s truyn vo l EventObject. Cc lp con ca EventListener c th ci t cc phng thc x l s kin.
9

Mt s lp s kin
EventObject (java.util)

AWTEvent

(java.awt)

TextEvent

ComponentEvent

ActionEvent

...

InputEvent

WindowEvent

ContainerEvent

KeyEvent

MouseEvent

(java.awt.event)
10

Mt s lp s kin
S kin cp thp: dng cho hu ht cc thnh phn
FocusEvent: t/chuyn focus InputEvent: s kin phm (KeyEvent) hoc chut (MouseEvent) ContainerEvent: thm hoc xo cc component WindowEvent: ng, m, di chuyn ca s ...

11

Mt s lp s kin
S kin cp cao: dng cho mt s thnh phn c th
ActionEvent: s kin sinh ra t cc thnh phn giao tip vi ngi dng nh nhn mt nt, chn menu ItemEvent: la chn mt item trong danh sch TextEvent: thay i gi tr ca hp text ...

12

Mt s interface nghe s kin


EventListener ContainerListener FocusListener KeyListener MouseListener WindowListener ActionListener ItemListener TextListener

13

Ci t qun l s kin
Xc nh i tng s gy ra s kin (event source). V d: nt bm. Xc nh s kin cn x l trn i tng gy s kin. V d: n nt. Xc nh i tng nghe s kin (event listener) v ci t cc phng thc tng ng. V d: chnh applet s nghe s kin. ng k i tng nghe trn i tng gy ra s kin. V d:
button.addActionListener(...);

14

Cc event source v event object


Event source Button Checkbox Choice Component Event ActionEvent ItemEvent ItemEvent FocusEvent MouseEvent KeyEvent Container List ContainerEvent ActionEvent ItemEvent Ch thch Nhn nt Chn, b chn mt item Chn, b chn mt item c chn Tng tc chut Tng tc bn phm Thm, bt component Nhp kp chut mt item Chn, b chn mt item
15

ComponentEvent n, hin, di chuyn

Cc event source v event object


Event source MenuItem Scrollbar TextField Window S kin ActionEvent Ch thch Chn mt menu item Thay i vn bn Kt thc thay i vn bn Thay i ca s

AdjustmentEvent Di chuyn thanh cun ActionEvent WindowEvent

TextComponent TextEvent

16

Bng tham kho i tng nghe v phng thc cn ci t


Event Class ActionEvent Listener Interface ActionListener Listener Methods actionPerformed()

AdjustmentEvent AdjustmentListener adjustmentValueChanged() ComponentEvent ComponentListener componentHidden() componentMoved() componentResized() componentShown() ContainerEvent FocusEvent ItemEvent ContainerListener FocusListener ItemListener componentAdded() componentRemoved() focusGained() focusLost() itemStateChanged()
17

Bng tham kho i tng nghe v phng thc cn ci t


Event Class KeyEvent Listener Interface KeyListener Listener Methods keyPressed() keyReleased() keyTyped() MouseEvent MouseListener mouseClicked() mousePressed() mouseReleased() MouseMotionListener TextEvent WindowEvent TextListener WindowListener mouseDragged() mouseMoved() textValueChanged() windowClosed() windowActivated()
18

ng k i tng nghe
ng k i tng nghe ta s dng tn phng thc c cu trc nh sau:
add + loi s kin + Listener(lp nghe s kin)

V d vi nt Button
addActionListener(ActionListener)

V d vi danh sch List


addActionListener(ActionListener) addItemListener(ItemListener)

19

Mt s thnh phn GUI


Event TextComponent Checkbox Container Object Component Label Button List Choice CheckboxGroup Panel Applet TextField

20

Nhn (Label)
Nhn c dng trnh by mt chui vn bn ra mn hnh Mt s phng thc ca Label:
public Label(); // to nhn public Label(String s); // to nhn vi ni dung s public Label(String s, int align); // to v canh l void setText(String s); // t ni dung nhn void setAlignment(int align); // canh l nhn ...

21

Nhn (Label)
import java.applet.Applet; import java.awt.*; public class DemoLabel extends Applet { private Label label; public void init() { Font font = new Font("Courier", Font.BOLD, 20); label = new Label("Thu nghiem voi Label"); label.setFont(font); add(label); } public void paint(Graphics g) { showStatus("Noi dung cua Label la: + label.getText()); }
22

Nhn (Label)

23

Nt nhn (Button)
Mt s phng thc ca Button
Button(); // to nt nhn Button(String s); // to nt nhn c tn s void setLabel(String s); // i tn nt String getLabel(); // ly tn nt nhn

i tng nghe s kin nhn nt cn ci t giao tip ActionListener

24

Nt nhn (Button)
import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class DemoButton extends Applet implements ActionListener { private Button blueButton; private Button whiteButton; private Button helloButton; public void init() { blueButton = new Button("Blue"); whiteButton = new Button("White"); helloButton = new Button("Hello"); blueButton.addActionListener(this); whiteButton.addActionListener(this); helloButton.addActionListener(this);
25

Nt nhn (Button)
add(blueButton); add(whiteButton); add(helloButton);

public void actionPerformed(ActionEvent event) { if (event.getSource() == helloButton) javax.swing.JOptionPane.showMessageDialog(this, "Hello !"); else { if (event.getSource() == blueButton) this.setBackground(Color.BLUE); else if (event.getSource() == whiteButton) this.setBackground(Color.WHITE); repaint(); } }
26

Nt nhn (Button)

27

vn bn (TextField)
vn bn cho php nhn d liu t bn phm trn mt dng Mt s phng thc
TextField(...); // cc cu t void setEditable(boolean b); // t/tt ch nhp void setEchoChar(char c); // t k t hin th

i tng nghe cn ci t 2 giao tip


ActionListener TextListener
Ci t phng thc textValueChanged();
28

vn bn (TextField)
import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class DemoTextField extends Applet implements ActionListener { private TextField txtEdit; private TextField txtReadOnly; private TextField txtPass; private final String PASSWORD = "Java"; public void init() { txtEdit = new TextField("Your name here"); txtPass = new TextField(12); txtPass.setEchoChar('*'); txtPass.addActionListener(this); txtReadOnly = new TextField("This text is read only"); txtReadOnly.setEditable(false);
29

vn bn (TextField)
add(txtEdit); add(txtPass); add(txtReadOnly);

public void actionPerformed(ActionEvent event) { if (txtPass.getText().equals(PASSWORD)) txtReadOnly.setText("Password is valid"); else txtReadOnly.setText("Invalid password !"); }

30

La chn (Choice)
Choice cung cp kh nng la chn mt trong s cc hng mc sn c Mt s phng thc
Choice(); // cu t void addItem(String s); // thm item l s String getItem(int index);// ly item c ch s index String getSeclectedItem(); // tr v item c chn int getSelectedIndex(); // tr v index ca item c chn

Lp nghe ci t giao tip ItemListener


Ci t phng thc itemStateChanged(...)
31

La chn (Choice)
import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class DemoChoice extends Applet implements ItemListener { private Choice choice; private TextField txtText; private Font font; public void init() { choice = new Choice(); choice.addItem("TimesRoman"); choice.addItem("Courier"); choice.addItem("Helvetica"); choice.addItemListener(this);

32

La chn (Choice)
txtText = new TextField("Sample Text", 16); txtText.setEditable(false); font = new Font(choice.getItem(0), Font.PLAIN, 12); txtText.setFont(font); add(choice); add(txtText);

public void itemStateChanged(ItemEvent event) { font = new Font(choice.getSelectedItem(), Font.PLAIN, 12); txtText.setFont(font); }

33

Checkbox (Hp nh du)


Checkbox cung cp cc hp tu chn cho ngi dng Mt s phng thc
Checkbox(...); // cc cu t void setLabel(String s); // t nhn mi boolean getState(); // ly trng thi hin ti

Lp nghe ci t giao tip ItemListener


Ci t phng thc itemStateChanged(...)

34

Checkbox (Hp nh du)


import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class DemoCheckbox extends Applet implements ItemListener { private Checkbox checkBold; private Checkbox checkItalic; private TextField txtText; public void init() { checkBold = new Checkbox("Bold"); checkItalic = new Checkbox("Italic"); checkBold.addItemListener(this); checkItalic.addItemListener(this); txtText = new TextField("Sample Text", 16); Font font = new Font("Courier", Font.PLAIN, 14); txtText.setFont(font);
35

Checkbox (Hp nh du)


add(txtText); add(checkBold); add(checkItalic);

public void itemStateChanged(ItemEvent event) { int valBold = Font.PLAIN; int valItalic = Font.PLAIN; if (checkBold.getState()) valBold = Font.BOLD; if (checkItalic.getState()) valItalic = Font.ITALIC; Font font = new Font("Courier", valBold + valItalic, 14); txtText.setFont(font); }

36

Checkbox v CheckboxGroup
Cc Checkbox c th c t trong mt CheckboxGroup to ra cc radio button. V d: To 3 radio button
// To 3 radio button thuc cng mt nhm. Ban u // radio1 c chn. Ti mi thi im ch c th chn mt // trong 3 radio. CheckboxGroup g = new CheckboxGroup(); Checkbox radio1 = new Checkbox(Radio1, g, true); Checkbox radio2 = new Checkbox(Radio2, g, false); Checkbox radio3 = new Checkbox(Radio3, g, false);

37

Checkbox v CheckboxGroup
// Cac import can thiet... public class DemoRadio extends Applet implements ItemListener { private Checkbox plain, bold, italic; private CheckboxGroup group; private TextField txtText; public void init() { group = new CheckboxGroup(); plain = new Checkbox("Plain", group, true); bold = new Checkbox("Bold", group, false); italic = new Checkbox("Italic", group, false); txtText = new TextField("Sample Text"); txtText.setFont(new Font("Courier", Font.PLAIN, 14)); plain.addItemListener(this); bold.addItemListener(this); italic.addItemListener(this);
38

Checkbox v CheckboxGroup
add(txtText); add(plain); add(italic); add(bold);

public void itemStateChanged(ItemEvent event) { int mode = 0; if (event.getSource() == plain) mode = Font.PLAIN; if (event.getSource() == italic) mode = Font.ITALIC; if (event.getSource() == bold) mode = Font.BOLD; txtText.setFont(new Font("Courier", mode, 14)); }

39

Danh sch (List)


List cho php ngi dng chn mt hay nhiu item t mt danh sch cc item Mt s phng thc
List(); // cu t mc nh List(int items, boolean ms); // cu t m rng String getSeclectedItem(); // ly li thnh phn c chn

Lp nghe ci t giao tip ItemListener v/hoc ActionListener


40

Danh sch (List)


// Cac import can thiet... public class DemoList extends Applet implements ItemListener, ActionListener { private List colorList; public void init() { colorList = new List(3, false); colorList.add("White"); colorList.add("Black"); colorList.add("Yellow"); colorList.add("Green"); colorList.addItemListener(this); colorList.addActionListener(this); add(colorList); }
41

Danh sch (List)


public void itemStateChanged(ItemEvent event) { List list = (List) event.getSource(); showStatus("Item " + list.getSelectedIndex() + " selected"); } public void actionPerformed(ActionEvent event) { List list = (List) event.getSource(); String s = list.getSelectedItem(); if (s.equals("White")) setBackground(Color.WHITE); if (s.equals("Black")) setBackground(Color.BLACK); if (s.equals("Yellow")) setBackground(Color.YELLOW); if (s.equals("Green")) setBackground(Color.GREEN); repaint(); }

42

Cc s kin chut
qun l cc s kin chut cn ci t giao tip
MouseListener MouseMotionListener

Cc phng thc ca MouseListener


void void void void void mousePressed(MouseEvent e); mouseClicked(MouseEvent e); mouseReleased(MouseEvent e); mouseEntered(MouseEvent e); mouseExited(MouseEvent e);
43

Cc s kin chut
Cc phng thc ca MouseMotionListener
void mouseDragged(MouseEvent e); void mouseMoved(MouseEvent e);

i tng MouseEvent
Cha cc thng tin v s kin chut

V d: Chng trnh v n gin

44

Cc s kin chut
// Cac import can thiet... public class DemoMouse extends Applet implements MouseListener { private Rectangle[] rects; private final int MAX_RECT = 100; private int numRects; public void init() { rects = new Rectangle[MAX_RECT]; numRects = 0; addMouseListener(this); setForeground(Color.RED); } public void paint(Graphics g) { for(int i=0; i< numRects; i++) g.fillRect(rects[i].x, rects[i].y, rects[i].width, rects[i].height); 45 }

Cc s kin chut
public void mouseClicked(MouseEvent e) { if (numRects < MAX_RECT) { rects[numRects++]=new Rectangle(e.getX(), e.getY(), 10, 10); repaint(); } } // Can cai dat tat ca cac phuong thuc cua giao tiep public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {}

46

Cc s kin chut

47

Cc lp adapter
Khi dng giao tip MouseListener ta phi ci t tt c cc phng thc ca n, ngay c khi ta ch dng mt trong s . Java cung cp mt s lp ci t sn nhng phng thc ny gi l cc lp Adapter). Ta ch cn tha k, ci t phng thc cn thit. Cc lp adapter cng nm trong gi java.awt.event

48

Cc lp adapter
Mt s lp adapter
Interface ComponentListener ContainerListener FocusListener KeyListener MouseListener MouseMotionListener WindowListener Adapter class ComponentAdapter ContainerAdapter FocusAdapter KeyAdapter MouseAdapter MouseMotionAdapter WindowAdapter
49

Cc s kin bn phm
Mt lp mun nghe s kin bn phm phi ci t giao tip KeyListener
void keyTyped(KeyEvent e); void keyPressed(KeyEvent e); void keyReleased(KeyEvent e);

Ch : C th s dng KeyAdapter thay cho dng giao tip KeyListener

50

Cc s kin bn phm
// Cac import can thiet... public class DemoKey extends Applet implements KeyListener { private String key; public void init() { addKeyListener(this); key = ""; } public void paint(Graphics g) { g.setFont(new Font("Arial", Font.BOLD, 72)); g.drawString(key, 100, 100); }

51

Cc s kin bn phm
public void keyTyped(KeyEvent e) { key = "" + e.getKeyChar(); repaint(); } public void keyPressed(KeyEvent e) {} public void keyReleased(KeyEvent e){}

52

Bi tp ti lp
Bi 1: Vit mt applet thc hin cng vic sau: khi chut c di chuyn vo applet th thng bo Hello Mouse, khi ra khi applet th thng bo Goodbye Mouse Bi 2: Vit mt applet cho php v ng thng bng chut (ging MS Paint)

53

B qun l b cc (Layout manager)


Java cung cp sn cc lp h tr trnh by cc thnh phn GUI. Mt s lp b cc n gin
FlowLayout: sp xp tun t BorderLayout: sp xp theo nm khu vc GridLayout: sp xp theo hng v ct

Ch :
Vi Applet v Panel, b cc mc nh l FlowLayout. C th thay i b cc bng hm setLayout
54

Lp FlowLayout
Cc thnh phn c a vo t tri sang phi, theo tng dng, nu ht dng s sang dng mi.

55

Lp FlowLayout
Mt s phng thc ca FlowLayout
FlowLayout(...); // cc cu t void setAlignment(int align); // cn l
public void init() { // tao flow layout can le phai FlowLayout layout = new FlowLayout(FlowLayout.RIGHT); setLayout(layout); add(new TextField(15)); add(new Button(Press me)); }

56

Lp BorderLayout
BorderLayout sp xp cc thnh phn theo 5 vng: EAST, WEST, SOUTH, NORTH, CENTER

57

Lp BorderLayout
// ... public void init() { // tao border layout setLayout(new BorderLayout()); add(new Button(Up), BorderLayout.NORTH); add(new Button(Left), BorderLayout.WEST); add(new Button(Right), BorderLayout.EAST); add(new Button(Down), BorderLayout.SOUTH); add(new Label(WELCOME, Label.CENTER), BorderLayout.CENTER); }

Ch : Khi add mt component theo BorderLayout cn ch r vng, nu khng component s khng c hin th.
58

Lp GridLayout
GridLayout sp xp cc thnh phn trong mt li c hng v ct. Kch thc cc component trong GridLayout l nh nhau.
private Button[] b; public void init() { // tao grid layout b = new Button[6]; b[0] = new Button("one"); b[1] = new Button("two"); b[2] = new Button("three"); b[3] = new Button("four"); b[4] = new Button("five"); b[5] = new Button("six"); setLayout( new GridLayout(3,2) ); for(int i=0; i<b.length; i++) add(b[i]); }

59

Khung cha (Container)


Khung cha l cc i tng trn c th cha cc thnh phn khc. Applet, Frame, Dialog, Panel l cc v d v khung cha.
Label 1

Container

Button TextField

Component

Label 2

60

Lp Panel (Vng cha)


Lp Panel k tha t Container. N c th c dng to ra cc giao din theo mun. V d: Mt giao din c th c nhiu panel sp xp theo mt layout nht nh, mi panel li c cc component sp xp theo mt layout ring. Ch : Panel c b cc mc nh l FlowLayout.
61

Lp Panel (Vng cha)


public void init() { Choice choice = new Choice(); choice.add("Red"); choice.add("Green"); choice.add("Blue"); Button ok = new Button("Ok"); Button cancel = new Button("Cancel"); Panel panel = new Panel(); panel.add(ok); panel.add(cancel); this.setLayout(new BorderLayout()); this.add(choice, BorderLayout.NORTH); this.add(panel, BorderLayout.CENTER);
62

Bi tp
1. Vit applet cho php nhp 3 h s a, b, c (bng TextField) sau gii phng trnh ax2 + bx + c = 0 v in kt qu. 2. Vit applet cho php nhp 3 h s a, b, c v 2 cn x1, x2 sau v th hm s ax2 + bx + c = 0 trong on [x1, x2]. 3. Vit applet to 3 nt bm. Bm nt 1 th v ngu nhin 100 ng thng ra mn hnh. Bm nt 2 th v ngu nhin 50 hnh trn. Bm nt 3 th v ngu nhin 50 hnh vung.
63

Bi tp
4. Vit mt applet cho php tnh ton n gin nh hnh bn. Ch ngi dng c th nhp d liu bng phm hoc chut.

64

Bi tp
5. Vit applet cho php ngi dng v cc hnh ch nht bng chut. Khi ngi dng n chut, ko v sau th chut th mt hnh ch nht tng ng s c v ra. M rng chng trnh: to 4 radio cho php chn v Oval, Rectangle, Fill Oval, Fill Rectangle. 6. Vit chng trnh cho php ngi dng iu khin mt qu bng. Trn mn hnh c cc nt l: To, Nh, Tri, Phi, Ln, Xung. Khi ngi dng n 1 nt th kch c/v tr ca qu bng s thay i theo. Yu cu to mt lp Ball ring bit.
65

Bi tp
7. Vit chng trnh m t tr chi d mn. Trn mn hnh c 3x3 nt bm v mi nt c th l c mn hoc khng (ngu nhin). Khi ngi dng nhn mt nt, nu nt khng c mn th cho php ngi dng n tip, cn khng th thng bo mn n v dng li. Lu l mi nt c mt s v ngi dng c th nhn phm s tng ng thay v nhn chut vo nt.

66

You might also like