Giáo trình Lập trình Java (Phần 2)
Chѭѫng 6:
LҰP TRÌNH ĈӖ HOҤ AWT
Mӝt khҧ năng cӫa Java là cho phép ta xây dӵng các ӭng dөng có giao diӋn ÿӗ hoҥ
hay còn gӑi là GUI (Grapthical User Interface). Khi Java ÿѭӧc phát hành, các thành phҫn
ÿӗ hoҥꢀÿѭӧc tұp trung vào thѭ viӋn mang tên Abstract Window Toolkit (AWT). Ĉӕi vӟi
Pӛi hӋ nӅn, thành phҫn AWT sӁꢀÿѭӧc ánh xҥ sang mӝt thành phҫn nӅn cө thӇ, bҵng cách sӱ
Gөng trӵc tiӃp mã native cӫa hӋ nӅn, chính vì vұy nó phө thuӝc rҩt nhiӅu vào hӋ nӅn và nó
còn gây lӛi trên mӝt sӕ hӋ nӅn. Vӟi bҧn phát hành Java 2, các thành phҫn giao diӋn ÿѭӧc
thay bҵng tұp hӧp các thành phҫn linh hoҥt, ÿa năng, mҥnh mӁ, ÿӝc lұp vӟi hӋ nӅn thuӝc
thѭ viӋn Swing. Phҫn lӟn các thành phҫn trong thѭ viӋn Swing ÿӅu ÿѭӧc tô vӁ trѭӧc tiӃp
trên canvas bҵng mã lӋnh cӫa Java, ngoҥi trӯ các thành phҫn là lӟp con cӫa lӟp
java.awt.Window hoһc Java.awt.Panel vӕn phҧi ÿӵѫc vӁ bҵng GUI trên nӅn cө thӇ. Thành
phҫn Swing ít phө thuӝc vào hӋ nӅn hѫn do vұy ít gһp lӛi hѫn và ÿһc biӋt nó sӱ dөng ít tài
nguyên cӫa hӋ thӕng hѫn các thành phҫn trong thѭ viӋn awt. Mһc dù các thành phҫn awt
Yүn ÿѭӧc hӛ trӧ trong Java 2 nhѭng, tuy nhiên Sun khuyên bҥn nên sӱ dөng các thành phҫn
Swing thay cho các thành phҫn awt, tuy nhiên các thành phҫn trong thѭ viӋn Swing không
thӇ thay tҩt cҧ các thành phҫn trong thѭ viӋn awt. Chúng chӍ thay thӃ mӝt phҫn cӫa awt
nhѭ: Button, Panel, TextFeild, v.v. Còn các lӟp trӧ giúp khác trong awt nhѭ : Graphics,
Color, Font, FontMetrics, v.v. vүn không thay ÿәi. Bên cҥnh ÿó các thành phҫn Swing còn
Vӱ dөng mô hình sӱ lý sӵ kiӋn cӫa awt.
I. Giӟi thiӋu vӅ hӋ thӕng ÿӗ hoҥ cӫa Java
1. Giͣi thi͏u chung
ThiӃt kӃ API cho lұp trình ÿӗ hoҥ cӫa Java là mӝt ví dө hoàn hҧo vӅ cách dùng lӟp, sӵ
NӃ thӯa và giao diӋn. API cho lұp trình ÿӝ hoҥ bao gӗm mӝt tұp rҩt nhiӅu lӟp nhҵm trӧ giúp
xây dӵng các thành phҫn giao diӋn khác nhau nhѭ: cӱa sә,nút ҩn, ô văn bҧn, menu, hӝp
kiӇm, v.v. Mӕi quan hӋ kӃ thӯa giӳa các thành phҫn này ÿѭӧc mô tҧ trong hình sau:
Componient Ĉây là lӟp (trӯu tѭӧng) cha cӫa mӑi lӟp giao diӋn ngѭӡi dùng. Lӟp này
cung cҩp các thuӝc tính, hành vi cѫ bҧn nhҩt cӫa tҩt cҧ các thành phҫn giao diӋn.
Container Là mӝt vұt chӭa dùng ÿӇ ghép nhóm các thành phҫn giao diӋn khác. Mӛi
Yұt chӭa có mӝt lӟp quҧn lý hiӇn thӏ, lӟp quҧn lý hiӇn thӏ có trách nhiӋm bӕ trí cách
thӭc hiӇn thӏ các thành phҫn bên trong. Hai vұt chӭa hay ÿѭӧc sӱ dөng nhҩt la
JFrame và JPanel.
Jcomponient Là lӟp cha cӫa mӑi thành phҫn Swing ligth weight, ÿѭӧc vӁ trӵc tiӃp
lên canvas bҵng mã lӋnh Java.
Window Ĉѭӧc sӱ dөng ÿӇ tҥo ra mӝt cӱa sә, Thông thѭӡng ta hay sӱ dөng hai lӟp
con cӫa nó là JFrame và JDialog.
JFrame là cӱa sә không lӗng bên trong cӱa sә khác.
JDialog là mӝt cӱa sәꢀÿѭӧc hiӇn thӏ dѭӟi dҥng modal.
JAplet là lӟp cha cӫa mӑi lӟp ӭng dөng aplet.
JPanel là mӝt vұt chӭa, lѭu giӳ các thành phҫn giao diӋn ngѭӡi dùng.
Graphics là lӟp trӯu tѭӧng cung cҩp ngӳ cҧnh ÿӗ hoҥꢀÿӇ vӁ các ÿӕi tѭӧng ÿӗ hoҥ
nhѭ: Ĉѭӡng thҷng, ÿѭӡng tròn, hình ҧnh…
Trang 120
Color lӟp này biӇu diӉn mӝt mҫu sҳc.
Font lӟp này biӇu thӏ cho mӝt font ÿӗ hoҥ.
FontMetrics là mӝt lӟp trӯu tѭӧng dùng ÿӇ xác ÿӏnh các thuӝc tính cӫa Font.
7ҩt cҧ các thành phҫn ÿӗ hoҥ trong thѭ viӋn Swing ÿѭӧc nhóm trong gói javax.swing. Ĉa
Vӕ các thành phҫn trong thѭ viӋn Swing ÿӅu có tiӃp ÿҫu ngӳ là ‘J’, Ví dө mӝt nút lӋnh trong
thѭ viӋn Swing có tên là JButton, mӝt memu có tên là JMenu.
Tҩt cҧ nhӳng lӟp khác ÿѭӧc liӋt kê trong hình dѭӟi ÿây
Chú ý: Ĉӯng pha trӝn các thành phҫn giao diӋn swing và awt trong cùng mӝt ӭng dөng.
Componient
Container
Panel
Applet
Frame
Dialog
JApplet
JFrame
JDialog
Window
AWTEvent
Object
Font
Các thành phɤn
khác trong gói
javax.swing ÿɉͣc kɼ
thͫa tͫ JComponent
FontMetric
Color
JComponent
Grapthics
BorderLayout
LayoutManage
FlowLayout
GridLayout
CardLayout
GridBagLayout
Chҷng hҥn nhѭꢀ ÿӯng nên ÿһt mӝt JButton vào mӝt Panel và ÿӯng nên ÿһt Button vào
JPanel. ViӋc làm này có thӇ gây lӛi.
Trang 121
0ӝt lӟp ÿѭӧc kӃ thӯa tӯ lӟp JComponent ÿѭӧc thӇ hiӋn trong hình sau:
JComponent
2. M͡t s͙ ph˱˯ng thͱc cͯa lͣp Component
/ӟp Component cung cҩp các thuӝc tính, phѭѫng thӭc chung cho các lӟp con cӫa
nó. Sau ÿây là mӝt sӕ phѭѫng thӭc cӫa lӟp Component :
- Dimension getSize(): cho lҥi ÿӕi tѭӧng thuӝc lӟp Dimension gӗm width (chiӅu rӝng),
height (chi͉u cao) xác ÿ͓nh kích th˱ͣc cͯa m͡t thành ph̯n tính theo pixel.
- void setSize(int width, int height) và void setSize(Dimension d) ÿһt lҥi kích thѭӟc cӫa
thành phҫn.
- Point getLocation(): cho lҥi tӑa ÿӝ (kiӇu Point) trên cùng bên trái (tӑa ÿӝ gӕc) cӫa thành
phҫn ÿang xét.
Trang 122
- void setLocation(int x, int y) và void setLocation(Point p):ꢀÿһt lҥi các tӑa ÿӝꢀÿѭӧc chӍ
ÿӏnh cho mӝt thành phҫn.
- Rectangle getBounds(): cho lҥi ÿѭӡng biên là hình chӳ nhұt Rectangle bao gӗm tӑa ÿӝ
Jӕc và chiӅu dài, chiӅu rӝng cӫa hình chӳ nhұt.
- void setBounds(int x, int y) và void setBounds(Rectangle r):ÿһt lҥi ÿѭӡng biên cho mӝt
thành phҫn.
- void setForeground(Color c):ÿѭӧc sӱ dөng ÿӇꢀÿһt màu vӁ cho thành phҫn ÿӗ hӑa
- void setBackground(Color c):ÿ̿t màu n͉n cho thành ph̯n ÿ͛ h͕a. Các tham sӕ cӫa hai
hàm này là ÿӕi tѭӧng cӫa lӟp Color sӁꢀÿѭӧc giӟi thiӋu ӣ phҫn sau.
- Font getFont():ꢀÿѭӧc sӱ dөng ÿӇ biӃt ÿѭӧc font cӫa các chӳꢀÿang xӱ lý trong thành
phҫn ÿӗ hӑa.
- void setFont(Font f):ÿһt lҥi font chӳ cho mӝt thành phҫn.
- void setEnabled(boolean b):1Ӄu ÿӕi sӕ b cӫa hàm getEnabled() là true thì thành phҫn
ÿang xét hoҥt ÿӝng bình thѭӡng, nghƭa là có khҧ năng kích hoҥt (enable), có thӇ trҧ lӡi các
yêu cҫu cӫa ngѭӡi sӱ dөng và sinh ra các sӵ kiӋn nhѭ mong muӕn. Ngѭӧc lҥi, nӃu là false
thì thành phҫn tѭѫng ӭng sӁ không kích hoҥt ÿѭӧc, nghƭa là không thӇ trҧ lӡi ÿѭӧc các yêu
Fҫu cӫa ngѭӡi sӱ dөng.
- Lѭu ý: Tҩt cҧ các thành phҫn giao diӋn khi khӣi tҥo ÿӅu ÿѭӧc kích hoҥt
- void setVisible(boolean b):0ӝt thành phҫn ÿӗ hӑa có thӇꢀÿѭӧc hiӇn thӏ lên màn hình
(nhìn thҩy ÿѭӧc) hoһc bӏ che giҩu tùy thuӝc vào ÿӕi sӕ cӫa hàm setVisible() là true hay
false.
3. Lͣp Container
/ӟp Container là lӟp con cӫa lӟp trӯu tѭӧng Component. Các lӟp chӭa (lӟp con cӫa
Container) cung cҩp tҩt cҧ các chӭc năng ÿӇ xây dӵng các giao diӋn ÿӗ hӑa ӭng dөng, trong
ÿó có phѭѫng thӭc add() ÿѭӧc nҥp chӗng dùng ÿӇ bә sung mӝt thành phҫn vào vұt chӭa và
phѭѫng thӭc remove() cNJng ÿѭӧc nҥp chӗng ÿӇ gӥ bӓ mӝt thành phҫn ra khӓi vұt chӭa.
4. T̩o ra Frame
/ӟp JFrame là lӟp con cӫa lӟp Frame (Frame là lӟp con cӫa lӟp Window) ÿѭӧc sӱ
Gөng ÿӇ tҥo ra nhӳng cӱa sә cho các giao diӋn ӭng dөng GUI.
.ӏch bҧn chung ÿӇ tҥo ra mӝt cӱa sә là:
- 7ҥo ra mӝt frame có tiêu ÿӅ gì ÿó, ví dө “My Frame” :
JFrame myWindow= new JFrame(“My Frame”);
- Xây dӵng mӝt cҩu trúc phân cҩp các thành phҫn bҵng cách sӱ dөng hàm
myWindow.getContentPane().add() ÿ͋ bә sung thêm JPanel hoһc nhӳng thành phҫn
giao diӋn khác vào Frame:
Vídө:
myWindow.getContentPane().add(new JButton(“OK”));// Ĉѭa vào mӝt nút
(JButton) có tên “OK” vào frame
- Ĉһt lҥi kích thѭӟc cho frame sӱ dөng hàm setSize():
myWindow.setSize(200, 300);// Ĉһt lҥi khung frame là 200 ( 300
- Gói khung frame ÿó lҥi bҵng hàm pack():
myWindow.pack();
- Cho hiӋn frame:
myWindow.setVisible(true);
Trang 123
II. Trình quҧn lý hiӇn thӏ trong Java
Khi thiӃt kӃ giao diӋn ÿӗ hӑa cho mӝt ӭng dөng, chúng ta phҧi quan tâm ÿӃn kích
thѭӟc và cách bӕ trí (layout) các thành phҫn giao diӋn nhѭ: JButton, JCheckbox,
JTextField, v.v. sao cho ti͏n lͫi nh̭t ÿ͙i vͣi ng˱ͥi s͵ dͭng. Java có các lӟp ÿҧm nhiӋm
nhӳng công viӋc trên và quҧn lý các thành phҫn giao diӋn GUI bên trong các vұt chӭa.
%ҧng sau cung cҩp bӕn lӟp quҧn lý layout (cách bӕ trí và sҳp xӃp) các thành phҫn GUI.
Tên lӟp
Mô tҧ
FlowLayout
XӃp các thành phҫn giao diӋn trѭӟc tiên theo hàng tӯ trái qua phҧi,
sau ÿó theo cӝt tӯ trên xuӕng dѭӟi. Cách sҳp xӃp này là mһc ÿӏnh
ÿӕi vӟi Panel, JPanel ,Applet và JApplet.
GridLayout
Các thành phҫn giao diӋn ÿѭӧc sҳp xӃp trong các ô lѭӟi hình chӳ
nhұt lҫn lѭӧt theo hàng tӯ trái qua phҧi và theo cӝt tӯ trên xuӕng
Gѭӟi trong mӝt phҫn tӱ chӭa. Mӛi thành phҫn giao diӋn chӭa trong
Pӝt ô.
BorderLayout
Các thành phҫn giao diӋn (ít hѫn 5) ÿѭӧc ÿһt vào các vӏ trí theo các
Kѭӟng: north (bҳc), south (nam), west (tây), east (ÿông) và center
(trung tâm)). Cách s̷p x͇p này là m̿c ÿ͓nhꢀÿӕi vӟi lӟp Window,
Frame, Jframe, Dialog và JDialog.
GridBagLayout Cho phép ÿһt các thành phҫn giao diӋn vào lѭӟi hình chӳ nhұt,
nhѭng mӝt thành phҫn có thӇ chiӃm nhiӅu nhiӅu hѫn mӝt ô.
null
Các thành phҫn bên trong vұt chӭa không ÿѭӧc sҹp lҥi khi kích
thѭӟc cӫa vұt chӭa thay ÿәi.
Các phѭѫng pháp thiӃt ÿһt layout
ĈӇ lҩy vӅ layout hay ÿӇꢀÿһt lҥi layout cho vұt chӭa, chúng ta có thӇ sӱ dөng hai phѭѫng
thӭc cӫa lӟp Container:
LayoutManager getLayout();
void setLayout(LayoutManager mgr);
Các thành phҫn giao diӋn sau khi ÿã ÿѭӧc tҥo ra thì phҧi ÿѭӧc ÿѭa vào mӝt phҫn tӱ chӭa
nào ÿó. Hàm add() cӫa lӟp Container ÿѭӧc nҥp chӗng ÿӇ thӵc hiӋn nhiӋm vөꢀÿѭa các
thành phҫn vào phҫn tӱ chӭa.
Component add(Component comp)
Component add(Component comp, int index)
Cmponent add(Component comp, Object constraints)
Cmponent add(Component comp, Object constraints, int index)
Trong ÿó, ÿӕi sӕ index ÿѭӧc sӱ dөng ÿӇ chӍ ra vӏ trí cӫa ô cҫn ÿһt thành phҫn giao diӋn
comp vào. Ĉӕi sӕ constraints xác ÿӏnh các hѭӟng ÿӇꢀÿѭa comp vào phҫn tӱ chӭa.
Ngѭӧc lҥi, khi cҫn loҥi ra khӓi phҫn tӱ chӭa mӝt thành phҫn giao diӋn thì sӱ dөng các hàm
sau:
void remove(int index)
Trang 124
void remove(Component comp)
void removeAll()
1. Lͣp FlowLayout
Lӟp FlowLayout cung cҩp các hàm tҥo lұp ÿӇ sҳp hàng các thành phҫn giao diӋn:
FlowLayout()
FlowLayout(int aligment)
FlowLayout(int aligment, int horizongap, int verticalgap)
public static final int LEFT
public static final int CENTER
public static final int RIGHT
ꢀ
Ĉӕi sӕ aligment xác ÿӏnh cách sҳp theo hàng: tӯ trái, phҧi hay trung tâm,
horizongap và verticalgap là kho̫ng cách tính theo pixel giͷa các hàng các cӝt.
Trѭӡng hӧp mһc ÿӏnh thì khoҧng cách giӳa các hàng, cӝt là 5 pixel.
2. Lͣp GridLayout
/ӟp GridLayout cung cҩp các hàm tҥo lұp ÿӇ sҳp hàng các thành phҫn giao diӋn:
GridLayout()
GridLayout(int rows, int columns)
GridLayout(int rows, int columns, int hoiongap, int verticalgap)
Tҥo ra mӝt lѭӟi hình chӳ nhұt có rows ( columns ô có khoҧng cách giӳa các hàng
các cӝt là horizongap, verticalgap. Mӝt trong hai ÿӕi sӕ rows ho̿c columns có th͋ là
0, nh˱ng không th͋ c̫ hai, GridLayout(1,0) là tҥo ra lѭӟi có mӝt hàng.
3.Lͣp BorderLayout
/ӟp BorderLayout cho phép ÿһt mӝt thành phҫn giao diӋn vào mӝt trong bӕn hѭӟng: E̷c
(NORTH), nam (SOUTH), ÿông (EAST), tây (WEST) và ͧ giͷa (CENTER).
BorderLayout()
BorderLayout(int horizongap, int verticalgap)
Tҥo ra mӝt layout mһc ÿӏnh hoһc có khoҧng cách giӳa các thành phҫn (tính bҵng
pixel) là horizongap theo hàng và verticalgap theo cӝt.
Component add(Component comp)
void add(Component comp, Object constraint)
public static final String NORTH
public static final String SOUTH
public static final String EAST
public static final String WEST
public static final String CENTER
Trѭӡng hӧp mһc ÿӏnh là CENTER, ngѭӧc lҥi, có thӇ chӍꢀÿӏnh hѭӟng ÿӇꢀÿһt các thành
phҫn comp vào phҫn tӱ chӭa theo constraint là mӝt trong các hҵng trên.
III. Xӱ lý sӵ kiӋn trong Java
Các ӭng dөng vӟi GUI thѭӡng ÿѭӧc hѭӟng dүn bӣi các sӵ kiӋn (event). ViӋc nhҩn
Pӝt nút, mӣ, ÿóng các Window hay gõ các ký tӵ tӯ bàn phím, v.v. ÿӅu tҥo ra các sӵ kiӋn
(event) và ÿѭӧc gӱi tӟi cho chѭѫng trình ӭng dөng. Trong Java các sӵ kiӋn ÿѭӧc thӇ hiӋn
Eҵng các ÿӕi tѭӧng. Lӟp cѫ sӣ nhҩt, lӟp cha cӫa tҩt cҧ các lӟp con cӫa các sӵ kiӋn là lӟp
java.util.EventObject.
Trang 125
java.lang.Object
java.util.EventObject
java.awt.AWTEvent
java.awt.event
ActionEvent
AdjustmentEvent
ItemEvent
TextEvent
ComponentEven
ContainerEvent
FocusEvent
KeyEvent
PaintEvent
WindowEvent
InputEvent
MouseEven
Hình H7-20 Các lӟp xӱ lý các sӵ kiӋn
Các lӟp con cӫa AWTEvent ÿѭӧc chia thành hai nhóm:
Các lӟp mô tҧ vӅ ngӳ nghƭa cӫa các sӵ kiӋn,
Các lӟp sӵ kiӋn ӣ mӭc thҩp.
1. Ý nghƭa cͯa các lͣp
a. ActionEvent
6ӵ kiӋn này ÿѭӧc phát sinh bӣi nhӳng hoҥt thӵc hiӋn trên các thành phҫn cӫa GUI. Các
thành phҫn gây ra các sӵ kiӋn hành ÿӝng bao gӗm:
- JButton - khi m͡t nút button ÿ˱ͫc khích ho̩t,
- JList - khi m͡t mͭc trong danh sách ÿ˱ͫc kích ho̩t ÿúp,
- JmenuItem, JcheckBoxMenu, JradioMenu - khi m͡t mͭc trong thc ÿ˯n ÿ˱ͫc ch͕n,
- JTextField - khi gõ phím ENTER trong tr˱ͥng văn b̫n (text).
b. AdjustmentEvent
6ӵ kiӋn này xҭy ra khi ta ÿLӅu chӍnh (adjustment) giá trӏ thanh cuӕn (JScollBar)
Scrollbar - khi thӵc hiӋn mӝt lҫn căn chӍnh trong thanh trѭӧt Scrollbar.
/ӟp này có phѭѫng thӭc int getValue(): cho lҥi giá trӏ hiӋn thӡi ÿѭӧc xác ÿӏnh bӣi lҫn căn
chӍnh sau cùng.
c. ItemEvent
Các thành phҫn cӫa GUI gây ra các sӵ kiӋn vӅ các mөc gӗm có:
Trang 126
- JCheckbox - khi trҥng thái cӫa hӝp kiӇm tra Checkbox thay ÿәi.
- CheckboxMenuItem - khi trҥng thái cӫa hӝp kiӇm tra Checkbox ӭng vӟi mөc cӫa
thӵc ÿѫn thay ÿәi.
- JRadioButton- khi trҥng thái cӫa hӝp chӑn (Option) thay ÿәi.
- JList - khi mӝt mөc trong danh sách ÿѭӧc chӑn hoһc bӏ loҥi bӓ chӑn.
- JCompoBox - khi mӝt mөc trong danh sách ÿѭӧc chӑn hoһc bӏ loҥi bӓ chӑn.
/ӟp ItemEvent có phѭѫng thӭc Object getItem(): Cho l̩i ÿ͙i t˱ͫng ÿ˱ͫc ch͕n hay vͳa b͓
E͗ ch͕n.
d. TextEvent
Các thành phҫn cӫa GUI gây ra các sӵ kiӋn vӅ text gӗm có:
TextArea - khi kӃt thúc bҵng nhҩn nút ENTER,
TextField - khi kӃt thúc bҵng nhҩn nút ENTER.
e. ComponentEvent
6ӵ kiӋn này xuҩt hiӋn khi mӝt thành phҫn bӏꢀҭn ÿi/hiӇn ra hoһc thay thay ÿәi lҥi kích thѭӟc.
/ӟp ComponentEvent có phѭѫng thӭc:
Component getComponent()
Cho l̩i ÿ͙i t˱ͫng tham chi͇u ki͋u Component.
f. ContainerEvent
6ӵ kiӋn này xuҩt hiӋn khi mӝt thành phҫn ÿѭӧc bә sung hay bӏ loҥi bӓ khӓi vұt chӭa
(Container).
g. FocusEvent
6ӵ kiӋn loҥi này xuҩt hiӋn khi mӝt thành phҫn nhұn hoһc mҩt focus.
h. KeyEvent
Lӟp KeyEvent là lӟp con cӫa lӟp trӯu tѭӧng InputEvent ÿѭӧc sӱ dөng ÿӇ xӱ lý các
Vӵ kiӋn liên quan ÿӃn các phím cӫa bàn phím. Lӟp này có các phѭѫng thӭc:
int getKeyCode()
- Ĉӕi vӟi các sӵ kiӋn KEY_PRESSED hoһc KEY_RELEASED, hàm này ÿѭӧc sӱ dөng ÿӇ
nhұn lҥi giá trӏ nguyên tѭѫng ӭng vӟi mã cӫa phím trên bàn phím.
char getKeyChar()
- Ĉӕi vӟi các sӵ kiӋn KEY_PRESSED, hàm này ÿѭӧc sӱ dөng ÿӇ nhұn lҥi giá trӏ nguyên,
mã Unicode tѭѫng ӭng vӟi ký tӵ cӫa bàn phím.
i. MouseEvent
/ӟp MouseEvent là lӟp con cӫa lӟp trӯu tѭӧng InputEvent ÿѭӧc sӱ dөng ÿӇ xӱ lý các tín
hiӋu cӫa chuӝt. Lӟp này có các phѭѫng thӭc:
int getX()
int getY()
Point getPoint()
Các hàm này ÿѭӧc sӱ dөng ÿӇ nhұn lҥi tӑa ÿӝ x, y cӫa vӏ trí liên quan ÿӃn sӵ kiӋn do
chuӝt gây ra.
void translatePoint(int dx, int dy)
Hàm translate() ÿѭӧc sӱ dөng ÿӇ chuyӇn tӑa ÿӝ cӫa sӵ kiӋn do chuӝt gây ra ÿӃn (dx,
dy).
int getClickCount()
Trang 127
Hàm getClickCount() ÿӃm sӕ lҫn kích chuӝt.
j. PaintEvent
Sӵ kiӋn này xuҩt hiӋn khi mӝt thành phҫn ÿѭӧc vӁ lҥi, thӵc tӃ sӵ kiӋn này xҭy ra khi
phѭѫng thӭc paint()/ update() ÿѭӧc gӑi ÿӃn.
k. WindowEvent
Sӵ kiӋn loҥi này xuҩt hiӋn khi thao tác vӟi các Window, chҷng hҥn nhѭ: ÿóng,
phóng to, thu nhӓ.. mӝt cӱa sә. Lӟp này có phѭѫng thӭc:
Window getWindow()
Hàm này cho l̩i ÿ͙i t˱ͫng cͯa lͣp Window ͱng vͣi s ki͏n liên quan ÿӃn Window
ÿã xҧy ra.
KiӇu sӵ kiӋn
Nguӗn gây ra sӵ kiӋn
Phѭѫng thӭc ÿang ký, gõ bӓ Giao diӋn
ÿӕi tѭӧng lҳng nghe
addComponentlistener
removeActiontListener
Listener lҳng
nghe tѭѫng ӭng
AcitionListener
AcitionEvent
JButton
JList
TexField
JScrollbar
AdjustmentEvent
ItemEvent
AdjustmentListe
ner
addAdjustmentListener
removeAdjustmentListener
addItemListener
ItemListener
TextListener
JCheckbox
JCheckboxMenuItem
JRadioButton
JList
removeItemListener
JCompoBox
addTexListener
removeTextListener
TextEvent
JTextArea
JTexField
JTextPane
JEditorPane
ComponentListe
ner
addComponentListener
ComponentEvent Component
removeComponentListener
Container
addContainerListener
removeContainerListener
ContainerListen
er
ContainerEvent
Component
Component
Component
addFocusListener
removeFocusListener
FocusListener
KeyListener
FocusEvent
KeyEvent
addkeyListener
removeKeyListener
addMouseListener
MouseMotionLi
MouseEvent
Trang 128
remoMouseListener
stener
addMouseMotionListener
remoMouseMotionListener
Window
addWindowListener
WindowListener
WindowEvent
removeWindowListener
3. M͡t s͙ lͣp ÿL͉u hͫp
/ӟp ÿLӅu hӧp tѭѫng ӭng
Giao diӋn Listener lҳng nghe
AcitionListener
Không có lӟp ÿLӅu hӧp tѭѫng ӭng
AdjustmentListener
ItemListener
AdjustmentAdapter
Không có lӟp ÿLӅu hӧp tѭѫng ӭng
Không có lӟp ÿLӅu hӧp tѭѫng ӭng
TextListener
ComponentListener
ContainerListener
FocusListener
ComponentAdapter
ContainerAdapter
FocusAdapter
KeyListener
KeyAdapter
MouseMotionListener
WindowListener
MouseMotionAdapter
WindowAdapter
0͡t s͙ ví dͭ minh h͕a
/* The applet enables the user to enter the interest rate,the number of years,
and the loan amount. Clicking the compute button displays the monthly payment
and the total payment.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.TitledBorder;
import java.applet.Applet;
import javax.swing.*;
public class StudentApp extends JFrame implements ActionListener{
private JTextField tRate = new JTextField(10);
private JTextField tYear = new JTextField(10);
private JTextField tLoan = new JTextField(10);
private JTextField tTotal = new JTextField(10);
private JButton compute = new JButton("Compute mortgage");
public static void main(String[] args){
StudentApp fr = new StudentApp();
fr.setSize(400, 200);
fr.setTitle("Mortgage Application");
//fr.center();
fr.setVisible(true);
}
Trang 129
public StudentApp(){
tTotal.setEditable(false);
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(5,2));
p1.add(new Label("Interest Rate"));
p1.add(tRate);
p1.add(new Label("Years"));
p1.add(tYear);
p1.add(new Label("Loan Amount"));
p1.add(tLoan);
p1.add(new Label("Total Payment"));
p1.add(tTotal);
p1.setBorder(new TitledBorder("Enter interest rate, year and loan amount"));
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout(FlowLayout.RIGHT));
p2.add(compute);
// Add the components to the applet
getContentPane().add(p1,BorderLayout.CENTER);
getContentPane().add(p2,BorderLayout.SOUTH);
// Register listener
compute.addActionListener(this);
}
// Handler for the compute button
public void actionPerformed(ActionEvent e){
if(e.getSource() == compute){
// Get values from text fields
double interest = (Double.valueOf(tRate.getText())).doubleValue();
int year = (Integer.valueOf(tYear.getText())).intValue();
double loan = (Double.valueOf(tLoan.getText())).doubleValue();
// Compute the total and displays it
double m = loan * interest * year;
tTotal.setText(String.valueOf(m));
}
}
}
Sӱ dөng ListBox và nút lӋnh
import java.awt.*;
import java.awt.event.*;
class ChoiceList extends Frame implements ActionListener{
Label l1 = new Label("What is your favorite color");
Choice colors = new Choice();
Button bt = new Button("Exit");
public ChoiceList(String title){
super(title);
setLayout(new FlowLayout());
add(bt);
add(l1);
Trang 130
colors.addItem("White");
colors.addItem("Red");
colors.addItem("Orange");
colors.addItem("Green");
colors.addItem("Yellow");
colors.addItem("Blue");
add(colors);
bt.addActionListener(this);
}
public void actionPerformed(ActionEvent ev){
if(ev.getSource() == bt){
System.exit(0);
}
}
// public void mouseExited(MouseEvent m){}
public static void main(String args[]){
ChoiceList t = new ChoiceList("Choice List");
t.setSize(300, 200);
t.show();
}
}
/* ClockGroup.java
* display a group of international clocks
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import javax.swing.Timer;
import java.text.*;
public class ClockGroup extends JApplet implements ActionListener{
private ClockPanel clockP1, clockP2, clockP3;
private JButton btResum, btSus;
public static void main(String[] arg){
JFrame fr = new JFrame("Clock Group Demo");
ClockGroup app = new ClockGroup();
fr.getContentPane().add(app, BorderLayout.CENTER);
app.init();
app.start();
fr.setSize(600, 350);
fr.setVisible(true);
}
public void init(){
// Panel p1 for holding 3 clocks
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1,3));
// Create a clock for Berlin
p1.add(clockP1 = new ClockPanel());
clockP1.setTitle("Berlin");
Trang 131
clockP1.clock.setTimeZoneID("ECT");
clockP1.clock.setLocale(Locale.GERMAN);
// Create a clock for SanFrancisco
p1.add(clockP2 = new ClockPanel());
clockP2.setTitle("San Francisco");
clockP2.clock.setTimeZoneID("PST");
clockP2.clock.setLocale(Locale.US);
// Create a clock for Taipei
p1.add(clockP3 = new ClockPanel());
clockP3.setTitle("Taipei");
clockP3.clock.setLocale(Locale.CHINESE);
clockP3.clock.setTimeZoneID("CTT");
// Panel p2 for holding 2 group buttons
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout());
p2.add(btResum = new JButton("Resume All"));
p2.add(btSus = new JButton("Suspend All"));
// Add p1, p2 into the applet
getContentPane().setLayout(new BorderLayout());
getContentPane().add(p1,BorderLayout.CENTER);
getContentPane().add(p2,BorderLayout.SOUTH);
// Register listener
btResum.addActionListener(this);
btSus.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == btResum){
// Start all clock
clockP1.resume();
clockP2.resume();
clockP3.resume();
}
else if (e.getSource() == btSus){
// Start all clock
clockP1.suspend();
clockP2.suspend();
clockP3.suspend();
}
}
}
class ClockPanel extends JPanel implements ActionListener{
private JLabel labelT;
protected Clock clock = null;
private JButton btResum, btSus;
public ClockPanel(){
JPanel bt = new JPanel();
bt.add(btResum = new JButton("Resum"));
bt.add(btSus = new JButton("Suspend"));
// Set BorderLayout for the ClockPanel
Trang 132
setLayout(new BorderLayout());
// Add title label to the north of the panel
add(labelT = new JLabel(), BorderLayout.NORTH);
labelT.setHorizontalAlignment(JLabel.CENTER);
// Add the clock to the center of the panel
add(clock = new Clock(),BorderLayout.CENTER);
add(bt,BorderLayout.SOUTH);
// Register
btResum.addActionListener(this);
btSus.addActionListener(this);
}
public void setTitle(String title){
labelT.setText(title);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == btResum){
clock.resume();
}
else if (e.getSource() == btSus){
clock.suspend();
}
}
public void resume(){
if(clock != null) clock.resume();
}
public void suspend(){
if(clock != null) clock.suspend();
}
}
class Clock extends StillClock implements ActionListener{
protected Timer timer;
public Clock(){
this(Locale.getDefault(), TimeZone.getDefault());
}
public Clock(Locale l, TimeZone t){
super(l, t);
timer = new Timer(1000,this);
timer.start();
}
public void resume(){
timer.start();
}
public void suspend(){
timer.stop();
}
public void actionPerformed(ActionEvent e){
repaint();
}
}
Trang 133
// Display a clock in JPanel
class StillClock extends JPanel{
protected TimeZone timeZ;
protected int xC, yC;
protected int clockR;
protected DateFormat form;
public StillClock(){
this(Locale.getDefault(), TimeZone.getDefault());
}
public StillClock(Locale l, TimeZone t){
setLocale(l);
this.timeZ = t;
}
public void setTimeZoneID(String newT){
timeZ = TimeZone.getTimeZone(newT);
}
// Override the paintComponent to display a clock
public void paintComponent(Graphics g){
super.paintComponent(g);
clockR = (int)(Math.min(getSize().width,getSize().height)*0.7*0.5);
xC = (getSize().width)/2;
yC = (getSize().height)/2;
// Draw circle
g.setColor(Color.black);
g.drawOval(xC-clockR, yC - clockR, 2*clockR,2*clockR);
g.drawString("12", xC - 5, yC - clockR);
g.drawString("9", xC - clockR-10, yC + 3);
g.drawString("3", xC + clockR, yC + 3);
g.drawString("6", xC + 3, yC + clockR + 10);
// Get current time using GregorianCalendar
GregorianCalendar cal = new GregorianCalendar(timeZ);
// Draw second hand
int second = (int) cal.get(GregorianCalendar.SECOND);
int sLen = (int)(clockR *0.9);
int xS = (int)(xC+sLen*Math.sin(second*(2*Math.PI/60)));
int yS = (int)(yC-sLen*Math.cos(second*(2*Math.PI/60)));
g.setColor(Color.red);
g.drawLine(xC, yC, xS, yS);
// Draw minut hand
int minute = (int) cal.get(GregorianCalendar.MINUTE);
int mLen = (int)(clockR *0.75);
int xM = (int)(xC+mLen*Math.sin(minute*(2*Math.PI/60)));
int yM = (int)(yC-mLen*Math.cos(minute*(2*Math.PI/60)));
g.setColor(Color.blue);
g.drawLine(xC, yC, xM, yM);
// Draw hour hand
int hour = (int) cal.get(GregorianCalendar.HOUR_OF_DAY);
int hLen = (int)(clockR *0.6);
int xH = (int)(xC+hLen*Math.sin((hour+minute/60.0)*(2*Math.PI/12)));
Trang 134
int yH = (int)(yC-hLen*Math.cos((hour+minute/60.0)*(2*Math.PI/12)));
g.setColor(Color.green);
g.drawLine(xC, yC, xH, yH);
// Set display form in specified style, locale, and timzone
form = DateFormat.getDateTimeInstance(
DateFormat.MEDIUM,DateFormat.LONG, getLocale());
form.setTimeZone(timeZ);
// Display current date
String today = form.format(cal.getTime());
FontMetrics fm = g.getFontMetrics();
g.drawString(today, (getSize().width-fm.stringWidth(today))/2,
yC+clockR+30);
}
}
6ӱ dөng các ÿLӅu khiӇn
package welcome;
import java.awt.*;
import java.awt.event.*;
public class ComponentTest extends Frame implements
ActionListener,MouseListener
{ TextField tf1=new TextField(30);
TextField tf2 = new TextField(40);
Label label1 = new Label("This is a way to use component...");
Checkbox b1 = new Checkbox("Red", true);
Checkbox b2 = new Checkbox("Blue", true);
CheckboxGroup cb = new CheckboxGroup();
Checkbox bg1 = new Checkbox("Small", cb, true);
Checkbox bg2 = new Checkbox("Large", cb, true);
TextArea ta = new TextArea(3, 25);
Choice colors = new Choice();
Button btnResult = new Button("Double is");
Button btnExt = new Button("Exit");
PopupMenu optionsMenu = new PopupMenu("Options");
public ComponentTest(String title) {
super(title);
setLayout(new FlowLayout());
add(label1);
add(ta);
add(tf1);
add(tf2);
add(b1);
add(b2);
add(bg1);
add(bg2);
colors.addItem("While");
colors.addItem("Red");
colors.addItem("Oranges");
Trang 135
colors.addItem("Green");
colors.addItem("Yellow");
colors.addItem("Blue");
colors.addItem("Black");
add(colors);
add(btnResult);
add(btnExt);
btnResult.addActionListener(this);
btnExt.addActionListener(this);
MenuBar mbar = new MenuBar();
setMenuBar(mbar);
Menu fileMenu = new Menu("File");
mbar.add(fileMenu);
fileMenu.addActionListener(this);
MenuItem newItem = new MenuItem("New");
fileMenu.add(newItem);
MenuItem openItem = new MenuItem("Open");
fileMenu.add(openItem);
fileMenu.addSeparator();
MenuItem saveItem = new MenuItem("Save");
fileMenu.add(saveItem);
fileMenu.addSeparator();
MenuItem exitItem = new MenuItem("Exit");
fileMenu.add(exitItem);
exitItem.addActionListener(this);
Menu editMenu = new Menu("Edit");
mbar.add(editMenu);
editMenu.addActionListener(this);
MenuItem cutItem = new MenuItem("Cut");
editMenu.add(cutItem);
MenuItem copyItem = new MenuItem("Copy");
editMenu.add(copyItem);
fileMenu.addSeparator();
MenuItem paseItem = new MenuItem("Pase");
editMenu.add(paseItem);
editMenu.add(optionsMenu);
//PopupMenu optionsMenu=new PopupMenu("Options");
optionsMenu.addActionListener(this);
MenuItem readItem = new MenuItem("Read Only");
optionsMenu.add(readItem);
optionsMenu.addSeparator();
Menu formatMenu = new Menu("Format text");
optionsMenu.add(formatMenu);
optionsMenu.addSeparator();
CheckboxMenuItem insertItem = new CheckboxMenuItem("Insert", true);
formatMenu.add(insertItem);
formatMenu.addSeparator();
CheckboxMenuItem overtypeItem = new CheckboxMenuItem("Over type", false);
Trang 136
formatMenu.add(overtypeItem);
formatMenu.addSeparator();
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == btnResult) {
int num = Integer.parseInt(tf1.getText()) * 2;
tf2.setText(String.valueOf(num));
}
if (ae.getSource() == btnExt) {
System.exit(0);
}
if (ae.getActionCommand().equals("Exit")) {
System.exit(0);
}
if (ae.getActionCommand().equals("Open")) {
System.out.println("You pressed the menuItem Open...");
label1.setText("Open");
}
}
public void mouseEntered(MouseEvent m) { }
public void mouseExited(MouseEvent m) { }
public void mouseClicked(MouseEvent m) {
optionsMenu.show(this, m.getX(), m.getY());
}
public void mouseReleased(MouseEvent m) { }
public void mousePressed(MouseEvent m) { }
public static void main(String args[]) {
ComponentTest c = new ComponentTest("Vi du dung thu vien java.awt.*");
c.setSize(500, 300);
c.show();
}
}
/*
The program has 4 buttons labeled Add, Sub, Mul, Div and also create a menu
to perform the same operation. The user will also create to perform the
same operation. The user can choose the operation either from buttons or
from menu selections. Fig. The following contains a sample run of the
program.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MenuDemo1 extends JFrame implements ActionListener{
private JTextField num1, num2, res;
private JButton btAdd, btSub, btMul,btDiv;
private JMenuItem mAdd, mSub,mMul, mDiv, mClose;
public static void main(String[] arg){
MenuDemo1 fr = new MenuDemo1();
fr.pack();
Trang 137
fr.setVisible(true);
}
public MenuDemo1(){
setTitle("Menu Demo");
JMenuBar mb = new JMenuBar();
setJMenuBar(mb);
JMenu opMenu = new JMenu("Operation");
opMenu.setMnemonic('O');
mb.add(opMenu);
JMenu exitMenu = new JMenu("Exit");
exitMenu.setMnemonic('E');
mb.add(exitMenu);
opMenu.add(mAdd = new JMenuItem("Add", 'A'));
opMenu.add(mSub = new JMenuItem("Sub", 'S'));
opMenu.add(mMul = new JMenuItem("Mul", 'M'));
opMenu.add(mDiv = new JMenuItem("Div", 'D'));
exitMenu.add(mClose = new JMenuItem("Close", 'C'));
mAdd.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
ActionEvent.CTRL_MASK));
mSub.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
ActionEvent.CTRL_MASK));
mMul.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M,
ActionEvent.CTRL_MASK));
mDiv.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D,
ActionEvent.CTRL_MASK));
JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout());
p1.add(new JLabel("Number 1"));
p1.add(num1 = new JTextField(4));
p1.add(new JLabel("Number 2"));
p1.add(num2 = new JTextField(4));
p1.add(new JLabel("Result"));
p1.add(res = new JTextField(4));
res.setEditable(false);
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout());
p2.add(btAdd = new JButton("Add"));
p2.add(btSub = new JButton("Sub"));
p2.add(btMul = new JButton("Mul"));
p2.add(btDiv = new JButton("Div"));
getContentPane().setLayout(new BorderLayout());
getContentPane().add(p1, BorderLayout.CENTER);
getContentPane().add(p2, BorderLayout.SOUTH);
btAdd.addActionListener(this);
btSub.addActionListener(this);
Trang 138
btMul.addActionListener(this);
btDiv.addActionListener(this);
mAdd.addActionListener(this);
mSub.addActionListener(this);
mMul.addActionListener(this);
mDiv.addActionListener(this);
mClose.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
String comm = e.getActionCommand();
if(e.getSource() instanceof JButton){
if("Add".equals(comm))
calculate('+');
else if ("Sub".equals(comm))
calculate('-');
else if ("Mul".equals(comm))
calculate('*');
else if ("Div".equals(comm))
calculate('/');
}
else if (e.getSource() instanceof JMenuItem){
if("Add".equals(comm))
calculate('+');
else if ("Sub".equals(comm))
calculate('-');
else if ("Mul".equals(comm))
calculate('*');
else if ("Div".equals(comm))
calculate('/');
else if ("Close".equals(comm))
System.exit(0);
}
}
private void calculate(char op){
int n1 = (Integer.parseInt(num1.getText().trim()));
int n2 = (Integer.parseInt(num2.getText().trim()));
int r = 0;
switch( op){
case '+': r = n1 + n2; break;
case '-': r = n1 - n2; break;
case '*': r = n1 * n2; break;
case '/': r = n1 / n2; break;
}
res.setText(String.valueOf(r));
}
}
/ұp trình menu
Trang 139
Tải về để xem bản đầy đủ
Bạn đang xem 20 trang mẫu của tài liệu "Giáo trình Lập trình Java (Phần 2)", để tải tài liệu gốc về máy hãy click vào nút Download ở trên
File đính kèm:
- giao_trinh_lap_trinh_java_phan_2.pdf