Upload
thach-vy
View
35
Download
0
Embed Size (px)
DESCRIPTION
Bài giảng JAVA cĂn bản về giao diện
Citation preview
Bi 5:
GRAPHICAL USER INTERFACE
1
Ni dung
2
Tng quan v Graphical User Interface (GUI)
Containment Hierarchy
Layout Manager
Swing components
Tng quan GUI
AWT: cung cp cc gi c bn lp trnh giao din, c s dng trong cc phin bn trc jdk1.2 (java2)
Swing: c nhiu chc nng hn AWT, xy dng chng trnh d dng mm do hn. c a vo t jdk1.2
Swt: c pht trin bi IBM
Swing Components thng c tn bt u vi 'J'
o AWT c lp Panel
o Swing c lp tng ng l JPanel
C th s dng plug-in h tr:
o Eclipse: WindowsBuilder Pro
o Netbean: tch hp3
Tng quan GUI (tt)
Th vin h tr lp trnh giao din trong Java
AWT (Abstract Windows Toolkits)
import java.awt.*;
Swing (Java Foundation Classes Package)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
Tt c Swing component c tn bt u vi J
4
Swing API
Java Foundation Classes (JFC) cung cp mt tp cc
chc nng gip xy dng cc ng dng GUI.
Gi Swing l 1 thnh phn ca JFC
S dng lnh: import javax.swing.*
u im ca Swing so vi AWT:
o Cung cp thm cc i tng mi xy dng giao din
ha
o look-and-feel: ty bin cc thnh phn giao din ca
Swing nhn ging nh cc thnh phn giao din ca HH
o H tr cc thao tc s dng bn phm thay chut
o S dng ti nguyn hiu qu hn5
6Java GUI hierarchy
Object
Color
ContainerComponent
LayoutManager
Panel
Window
Applet
Frame
Dialog
JComponent
JApplet
JFrame
JDialog
Swing
AWT
lightweight heavyweight
Dimension
Font
FontMetrics
Graphics
6
7Java GUI hierarchy (tt)
JComponent
JMenuBar
AbstractButton
JScrollPane
JPanel
JTextComponent
JLabel
JComboBox
JMenuItem
JButton
JTextArea
JTextField JPasswordField
etc. Swing
lightweight heavyweight
7
Swing Components
Swing Components c nhiu mc khc nhau:o frame, cn gi main window (JFrame)
o panel, hoc pane (JPanel)
o button (JButton)
o label (JLabel)
Cc mc ny qui nh cc Component trong 1 ng dng GUI kt hp vi nhau.
Cch kt hp ny gi l Swing Containment Hierarchy
8
Khi nim container
L thnh phn m c th cha cc thnh phn khc, c th v v t mu.
o Frame/JFrame, Panel/JPanel, Dialog/JDialog,
ScrollPane/JScrollPane,
Gn component vo khung cha
o containerObj.add(compObj);
Ly thng tin ca component
o objectName.get( );
Gn thng tin cho component
o objectName.set( );9
Nguyn tc xy dng GUI trong java
La chn 1 container: Frame/JFrame, Window/JWindow, Dialog/JDialog,
To cc iu khin: (buttons, text areas..)
a cc iu khin vo vng cha
Sp xp cc iu khin(layout)
Thm cc x l s kin (Listeners)
10
Containment Hierarchy
Frame: Top-level container: JFrame, JDialog, JApplet
11
Containment Hierarchy (tt)
Top Level
Container
Intermediate
Container
Atomic Component NAtomic Component N Atomic Component N
12
Containment Hierarchy (tt)
Top Level
(JFrame)
Intermediate
(JPanel)
Atomic
(JButton)
Atomic
(JLabel)
13
Containment Hierarchy (tt)
Top Level Containers
o L ni hin th cc Component khc
o V d:
JFrame: s dng cho cc ca s chnh ca chng trnh
JDialog: ca s thng bo
JApplet: s dng trn trnh duyt
14
Containment Hierarchy (tt)
Top Level Containers: JFrameo L ca s chnh, dng cha cc thnh phn giao din khc.
ng vai tr l mt container
o Hm khi to JFrame() JFrame(String title)
o Cc thnh phn ha c a vo content pane, khng a
trc tip vo JFrame. V d:frame.getContentPane().add(b);
o JFrame cung cp 2 phng thc: getContentPane() tr li mt i tng ContentPane thuc lp
Container
setContentPane(JPanel): thit lp ni dung cho Content Pane15
V D JFrame
import javax.swing.*;
class Frame1 extends JFrame {
/* Construction of the frame */
public Frame1() {
this.setSize(350, 250);
this.setTitle("My First Java Frame");
}
}
public class AppFrame1 {
public static void main(String[ ] args) {
Frame1 frame = new Frame1();
frame.setVisible(true);
}
}
Ap
pF
ram
e1.j
av
a
closing window
350
25
016
Containment Hierarchy (tt)
Intermediate Containers
o Dng xc nh v tr ca cc Atomic Components
o Hoc cung cp c ch tng tc vi khung cha.
o V d:
JPanel
JScrollPane
JTabbedPane
17
Containment Hierarchy (tt)
Intermediate Containers: JPanel
o L container trung gian cha cc Atomic
Components
o Thng dng chia cc component trong ng dng
o Hm khi to:
JPanel();
JPanel(LayoutManager lm);
18
Containment Hierarchy (tt)
Atomic Componentso Khng cha cc Components khc
o Dng cung cp thng tin n ngi s dng
o Hoc ly thng tin t ngi s dng
o V d:
JButton JLabel JComboBox JTextField JTable
19
Containment Hierarchy (tt)
Mi Top Level Container c 1 intermediate Container gi l Content Pane
Cc atomic component phi gn vo content paneo V d
JFrame frame = new JFrame(...);
JPanel pane = new JPanel();
frame.getContentPane().add(pane);
20
Layout Manager
Khi nim: c dng iu khin cch trnh by vt l ca cc phn t GUI nh l button, textbox, option button
Cc loi layout khc nhau:
o Flow Layout
o Border Layout
o Grid Layout
o GridBag Layout
o Null Layout
o
Trnh qun l layout c thit lp bng cch gi phng thc setLayout( )21
Layout Manager: FlowLayout
L trnh qun l layout mc nh cho cc panel
Vi FlowLayout cc thnh phn s c xp xp t gctri trn n gc phi di ca mn hnh.
Cc hm khi to - constructor:
o public FlowLayout();
o public FlowLayout(int align); // Canh l bn phi
o public FlowLayout(int align, int hgap, int vgap);
align: c cc gi tr FlowLayout.LEFT, FlowLayout.CENTER, FlowLayout.RIGHT, FlowLayout.LEADING, hoc
FlowLayout.TRAILING
hgap, vgap: khong trng gia cc thnh phn22
FlowLayout (tt)
Flow Layout Left and Right Aligned
23
Layout Manager: BorderLayout
L trnh qun l layout mc nh cho Window, Frame vDialog
Trnh qun l ny c th xp xp n 5 thnh phn trongcontainer
Cc thnh phn c th c t vo 5 hng NORTH,EAST, SOUTH, WEST v CENTER ca container
V d: thm mt thnh phn vo vng North cacontainerJButton b1= new JButton(North Button); setLayout(new BorderLayout( )); add(b1, BorderLayout.NORTH);
24
BorderLayout (tt)
25
public void showBorderLayout(){
JFrame frame = new JFrame("Border Layout Demo");
frame.setSize(400,400);
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JButton("North Button"),BorderLayout.NORTH);
panel.add(new JButton("South Button"),BorderLayout.SOUTH);
panel.add(new JButton("West Button"),BorderLayout.WEST);
panel.add(new JButton("East Button"),BorderLayout.EAST);
panel.add(new JButton("Center Button"),BorderLayout.CENTER);
//frame.getContentPane().add(panel);
frame.add(panel);
frame.setVisible(true);
}
BorderLayout (tt)
26
Layout Manager: GridLayout
27
H tr vic chia container thnh mt li Cc thnh phn c b tr trong cc dng v ct Mt li nn cha t nht mt thnh phn Kiu layout ny c s dng khi tt c cc thnh phn
c cng kch thc
GridLayout layout = new GridLayout(no. of rows, no. of columns);
containerObj.setLayout(layout);
GridLayout
28
public void showGridLayout(){
JFrame frame = new JFrame("Border Layout Demo");
frame.setSize(400,400);
JPanel panel = new JPanel();
GridLayout gridLayout = new GridLayout(2,2);
panel.setLayout(gridLayout);
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));
panel.add(new JButton("Button 4"));
//frame.getContentPane().add(panel);
frame.add(panel);
frame.setVisible(true);
}
Layout Manager: GridBagLayout
B tr cc thnh phn mt cch chnh xc Cc thnh phn khng cn c cng kch thc Cc thnh phn c xp xp trong mt li cha cc
dng v cc ct Th t t cc thnh phn khng tun theo hng t tri-
sang-phi v trn-xung-di Hm constructor
GridBagLayout gb = new GridBagLayout( );
Lp GridBagLayoutConstraints lu tr tt c cc thngtin m lp GridLayout yu cu: V tr v kch thuc mithnh phn
29
GridBagLayout
30
Layout Manager: NullLayout
T do trong vic nh v tr v kch thc ca cc components
Gii php ny dng xc nh hon ton kch thc v v v tr ca component.
Frame fr = new Frame("NullLayout Demo");
fr.setLayout(null);
31
Swing Components
32
S Dng Swing Component
33
C cc phng thc add, set, get
Phng thc dng gn components:
o objectName.add( );
Phng thc dng ly thuc tnh:
o objectName.getxxx( );
Phng thc dng gn thuc tnh:
o objectName.setxxx( );
S dng Swing Components
34
JLabel
Label dng hin th mt chui vn bn, hnh nh
nhm m t thm thng tin cho cc i tng khc.
Cc constructor ca JLabel:JLabel()
JLabel(String text)
JLabel(String text,int hAlignment)
JLabel(Icon icon)
JLabel(Icon icon, int hAlignment)
JLabel(String text,Icon icon,int hAlignment)
hAlignment: c cc gi tr LEFT, CENTER, RIGHT,LEADING, hoc
TRAILING35
Cc thuc tnh JLabel
o text
o icon
o horizontalAlignment
o verticalAlignment
Using Labels
36
V D
37
JTextComponent
38
y l lp cha ca tt c cc lp hin th vn bn trong Swing
JTextField
Textfield l nhp d liu dng vn bn trn 1 dng.
Cc constructor ca JTextField:
JTextField()
o To mt text field trng c s ct xc nh.
JTextField(int columns)
o To mt text field vi vn bn c sn.
JTextField(String text)
o To mt text field vi vn bn c sn v s ct xc nh.
JTextField(String text, int columns)39
Cc thuc tnh JTextField
o text
o horizontalAlignment
o editable
o columns
40
Cc phng thc JTextField
o getText()
Tr v chui k t trong text field. o setText(String text)
t chui k t trong text field.o setEditable(boolean editable)
Cho php hoc v hiu ha son tho trong text field. Mc nh editable l true.
o setColumns(int)
Thit lp s ct trong textfield. Chiu di ca textfield c th thay i.
41
JTextArea
TextArea l khung cho php ngi s dng nhp vo
nhiu dng vn bn.
Cc constructor ca JTextArea:
JTextArea()
JTextArea(String s)
JTextArea(int rows, int columns)
JTextArea(String s, int rows, int columns)
42
Cc thuc tnh JTextArea
o text
o editable
o columns
o lineWrap
o wrapStyleWord
o rows
o lineCount
o tabSize
43
Cc phng thc JTextArea
o getColumns()
Tr v s ct trong textarea. o getLineCount()
Tr v s dng trong textareao insert(String str, int pos)
t chui vo mt v tr xc nh.o append(String str)
Thm chui vo cui textareao paramString()
Tr v on vn bn trong textarea
44
Swing Button Classes
JComponent
AbstractButton
JButton JToggleButton
JCheckBox JRadioButton
45
JButton
Button l mt thnh phn gy ra mt s kin hnh ng
khi c kch chut.
Cc constructor ca JButton:
JButton()
JButton(String text)
JButton(String text, Icon icon)
JButton(Icon icon)
46
Cc thuc tnh JButton
o text
o icon
o mnemonic
o horizontalAlignment
o verticalAlignment
o horizontalTextPosition
o verticalTextPosition
47
p ng cc s kin JButton
public void actionPerformed(ActionEvent e)
{
// Get the button label
String actionCommand = e.getActionCommand();
// Make sure the event source is Left button
if (e.getSource() instanceof JButton)
// Make sure it is the right button
if ("Left".equals(actionCommand))
System.out.println ("Button pressed!");
}
48
49
JToggleButton
Cc nt lnh thay i trng thi
o Nhn cc gi tr on/off hoc true/false
o Swing h tr cc kiu:
JCheckBox
JRadioButton
50
Item Event
c to ra khi ngi dng chn cc mc khc nhau trn JCheckBox, JRadioButton,..
Cc phng thc
o Object getItem(): tr v mc c chn
o int getStateChange():tr v trng thi trng thi ca
mc chn (DESELECTED/SELECTED)
51
Item Listener
o void itemStateChanged(ItemEvent e):c gi
thi hnh khi ngi dng chn hoc b chn 1 mc.
52
JCheckBox
Checkbox c dng cung cp cho ngi dng kh nng la chn
Cc contructor JCheckBox:JCheckBox()
JCheckBox(Icon icon)
JCheckBox(Icon icon, boolean selected)
JCheckBox(String text)
JCheckBox(String text, boolean selected)
JCheckBox(String text, Icon icon)
JCheckBox(String text, Icon icon, boolean selected)
JCheckBox(Action a)
53
JCheckBox (tt)
54
1 // Fig. 12.11: CheckBoxTest.java
2 // Creating Checkbox buttons.
3
4 // Java core packages
5 import java.awt.*;
6 import java.awt.event.*;
7
8 // Java extension packages
9 import javax.swing.*;
10
11 public class CheckBoxTest extends JFrame {
12 private JTextField field;
13 private JCheckBox bold, italic;
14
15 // set up GUI
16 public CheckBoxTest()
17 {
18 super( "JCheckBox Test" );
19
20 // get content pane and set its layout
21 Container container = getContentPane();
22 container.setLayout( new FlowLayout() );
23
24 // set up JTextField and set its font
25 field =
26 new JTextField( "Watch the font style change", 20 );
27 field.setFont( new Font( "Serif", Font.PLAIN, 14 ) );
28 container.add( field );
29
30 // create checkbox objects
31 bold = new JCheckBox( "Bold" );
32 container.add( bold );
33
34 italic = new JCheckBox( "Italic" );
35 container.add( italic );
CheckBoxTest.java
Line 13
Line 27
Lines 31-35
Declare two JCheckBox instances
Set JTextField font
to Serif, 14-point plain
Instantiate JCheckBoxs for bolding and
italicizing JTextField text, respectively
5
4
36
37 // register listeners for JCheckBoxes
38 CheckBoxHandler handler = new CheckBoxHandler();
39 bold.addItemListener( handler );
40 italic.addItemListener( handler );
41
42 setSize( 275, 100 );
43 setVisible( true );
44 }
45
46 // execute application
47 public static void main( String args[] )
48 {
49 CheckBoxTest application = new CheckBoxTest();
50
51 application.setDefaultCloseOperation(
52 JFrame.EXIT_ON_CLOSE );
53 }
54
55 // private inner class for ItemListener event handling
56 private class CheckBoxHandler implements ItemListener {
57 private int valBold = Font.PLAIN;
58 private int valItalic = Font.PLAIN;
59
60 // respond to checkbox events
61 public void itemStateChanged( ItemEvent event )
62 {
63 // process bold checkbox events
64 if ( event.getItem() == bold )
65
66 if ( event.getStateChange() == ItemEvent.SELECTED )
67 valBold = Font.BOLD;
68 else
69 valBold = Font.PLAIN;
70
CheckBoxTest.java
Lines 38-40
Line 61
Register JCheckBoxs to receive
events from CheckBoxHandler
When user selects JCheckBox,
CheckBoxHandler invokes
method itemStateChanges of all
registered listeners
5
4
71 // process italic checkbox events
72 if ( event.getSource() == italic )
73
74 if ( event.getStateChange() == ItemEvent.SELECTED )
75 valItalic = Font.ITALIC;
76 else
77 valItalic = Font.PLAIN;
78
79 // set text field font
80 field.setFont(
81 new Font( "Serif", valBold + valItalic, 14 ) );
82 }
83
84 } // end private inner class CheckBoxHandler
85
86 } // end class CheckBoxTest
CheckBoxTest.java
Lines 80-81Change JTextField font, depending on
which JCheckBox was selected
5
4
JRadioButton
Mt tp cc nt cho php ch la chn c mt ti mt thi im
Dng lp ButtonGroup to ra nhm
Cc contructor JRadioButton:o JRadioButton(Icon icon)
o JRadioButton(Icon icon, boolean selected)
o JRadioButton(String text)
o JRadioButton(String text, boolean selected)
o JRadioButton(String text, Icon icon)
o JRadioButton(String text, Icon icon, boolean selected)
o JRadioButton(Action a)
58
JRadioButton (tt)
59
1 // Fig. 12.12: RadioButtonTest.java
2 // Creating radio buttons using ButtonGroup and JRadioButton.
3
4 // Java core packages
5 import java.awt.*;
6 import java.awt.event.*;
7
8 // Java extension packages
9 import javax.swing.*;
10
11 public class RadioButtonTest extends JFrame {
12 private JTextField field;
13 private Font plainFont, boldFont, italicFont, boldItalicFont;
14 private JRadioButton plainButton, boldButton, italicButton,
15 boldItalicButton;
16 private ButtonGroup radioGroup;
17
18 // create GUI and fonts
19 public RadioButtonTest()
20 {
21 super( "RadioButton Test" );
22
23 // get content pane and set its layout
24 Container container = getContentPane();
25 container.setLayout( new FlowLayout() );
26
27 // set up JTextField
28 field =
29 new JTextField( "Watch the font style change", 25 );
30 container.add( field );
31
32 // create radio buttons
33 plainButton = new JRadioButton( "Plain", true );
34 container.add( plainButton );
35
RadioButtonTest.java
Lines 14-15
Line 16
JRadioButtons normally
appear as a ButtonGroup
Declare four JRadioButton instances
5
4
36 boldButton = new JRadioButton( "Bold", false);
37 container.add( boldButton );
38
39 italicButton = new JRadioButton( "Italic", false );
40 container.add( italicButton );
41
42 boldItalicButton = new JRadioButton(
43 "Bold/Italic", false );
44 container.add( boldItalicButton );
45
46 // register events for JRadioButtons
47 RadioButtonHandler handler = new RadioButtonHandler();
48 plainButton.addItemListener( handler );
49 boldButton.addItemListener( handler );
50 italicButton.addItemListener( handler );
51 boldItalicButton.addItemListener( handler );
52
53 // create logical relationship between JRadioButtons
54 radioGroup = new ButtonGroup();
55 radioGroup.add( plainButton );
56 radioGroup.add( boldButton );
57 radioGroup.add( italicButton );
58 radioGroup.add( boldItalicButton );
59
60 // create font objects
61 plainFont = new Font( "Serif", Font.PLAIN, 14 );
62 boldFont = new Font( "Serif", Font.BOLD, 14 );
63 italicFont = new Font( "Serif", Font.ITALIC, 14 );
64 boldItalicFont =
65 new Font( "Serif", Font.BOLD + Font.ITALIC, 14 );
66 field.setFont( plainFont );
67
68 setSize( 300, 100 );
69 setVisible( true );
70 }
RadioButtonTest.java
Lines 36-44
Lines 47-51
Lines 54-58
Instantiate JRadioButtons for
manipulating JTextField text font
Register JRadioButtons to
receive events from RadioButtonHandler
JRadioButtons belong to
ButtonGroup
5
4
71
72 // execute application
73 public static void main( String args[] )
74 {
75 RadioButtonTest application = new RadioButtonTest();
76
77 application.setDefaultCloseOperation(
78 JFrame.EXIT_ON_CLOSE );
79 }
80
81 // private inner class to handle radio button events
82 private class RadioButtonHandler implements ItemListener {
83
84 // handle radio button events
85 public void itemStateChanged( ItemEvent event )
86 {
87 // user clicked plainButton
88 if ( event.getItem() == plainButton )
89 field.setFont( plainFont );
90
91 // user clicked boldButton
92 else if (event.getItem() == boldButton )
93 field.setFont( boldFont );
94
95 // user clicked italicButton
96 else if (event.getItem() == italicButton )
97 field.setFont( italicFont );
98
99 // user clicked boldItalicButton
100 else if (event.getItem() == boldItalicButton )
101 field.setFont( boldItalicFont );
102 }
103
104 } // end private inner class RadioButtonHandler
105
106 } // end class RadioButtonTest
RadioButtonTest.java
Lines 85-104
Lines 88-102
When user selects JRadioButton,
RadioButtonHandler invokes
method itemStateChanged of all
registered listeners
Set font corresponding to
JRadioButton selected
5
4
JComboBox
JComboBox
oDng lit k danh sch cc mc m ngi dng c th
chn
oCn c gi l drop-down list
o Pht sinh s kin ItemEvent khi ngi s dng chn 1 mc
trong danh sch
Cc constructor Jcomboboxo JComboBox()
o JComboBox(ComboBoxModel asModel)
o JComboBox(Object []item)
6
3
JComboBox (tt)
6
4
2002 Prentice Hall, Inc. All rights reserved.
Outline1 // Fig. 12.13: ComboBoxTest.java2 // Using a JComboBox to select an image to display.
3
4 // Java core packages
5 import java.awt.*;
6 import java.awt.event.*;
7
8 // Java extension packages
9 import javax.swing.*;
10
11 public class ComboBoxTest extends JFrame {
12 private JComboBox imagesComboBox;
13 private JLabel label;
14
15 private String names[] =
16 { "bug1.gif", "bug2.gif", "travelbug.gif", "buganim.gif" };
17 private Icon icons[] = { new ImageIcon( names[ 0 ] ),
18 new ImageIcon( names[ 1 ] ), new ImageIcon( names[ 2 ] ),
19 new ImageIcon( names[ 3 ] ) };
20
21 // set up GUI
22 public ComboBoxTest()
23 {
24 super( "Testing JComboBox" );
25
26 // get content pane and set its layout
27 Container container = getContentPane();
28 container.setLayout( new FlowLayout() );
29
30 // set up JComboBox and register its event handler
31 imagesComboBox = new JComboBox( names );
32 imagesComboBox.setMaximumRowCount( 3 );
33
34 imagesComboBox.addItemListener(
35
ComboBoxTest.java
Lines 31-32
Line 34
Register JComboBox to receive events
from anonymous ItemListener
Instantiate JComboBox to
show three Strings from
names array at a time
5
4
2002 Prentice Hall, Inc. All rights reserved.
Outline36 // anonymous inner class to handle JComboBox events37 new ItemListener() {
38
39 // handle JComboBox event
40 public void itemStateChanged( ItemEvent event )
41 {
42 // determine whether check box selected
43 if ( event.getStateChange() == ItemEvent.SELECTED )
44 label.setIcon( icons[
45 imagesComboBox.getSelectedIndex() ] );
46 }
47
48 } // end anonymous inner class
49
50 ); // end call to addItemListener
51
52 container.add( imagesComboBox );
53
54 // set up JLabel to display ImageIcons
55 label = new JLabel( icons[ 0 ] );
56 container.add( label );
57
58 setSize( 350, 100 );
59 setVisible( true );
60 }
61
62 // execute application
63 public static void main( String args[] )
64 {
65 ComboBoxTest application = new ComboBoxTest();
66
67 application.setDefaultCloseOperation(
68 JFrame.EXIT_ON_CLOSE );
69 }
70
71 } // end class ComboBoxTest
ComboBoxTest.java
Lines 40-46
Lines 43-45
When user selects item in JComboBox,
ItemListener invokes method
itemStateChanged of all registered listeners
Set appropriate Icon
depending on user selection
5
4
JList
Jlist
oDanh sch cc mc chn
oC th chn 1 hoc nhiu mc
oCho php sp xp d liu hin th, phn nhm
oC th hin th chui v icon
oKhng h tr doublclik chut
o Pht sinh ListSelectionEvent khi ngi dng chn
Cc constructor Jlisto JList()
o JList(ListModel dataModel)
o JList(Object []listData)6
7
Jlist (tt)
Cc phng thco JList(Object[] listData)
o int getSelectedIndex()
o Object[] getSelectedValues()
o void setListData(Object[] listData)
o void setSelectedIndex(int idx)
ListSelectionListenero void valueChanged(ListSelectionEvent e)
6
8
Jlist Demo
5
4
2002 Prentice Hall, Inc. All rights reserved.
Outline1 // Fig. 12.14: ListTest.java
2 // Selecting colors from a JList.
3
4 // Java core packages
5 import java.awt.*;
6
7 // Java extension packages
8 import javax.swing.*;
9 import javax.swing.event.*;
10
11 public class ListTest extends JFrame {
12 private JList colorList;
13 private Container container;
14
15 private String colorNames[] = { "Black", "Blue", "Cyan",
16 "Dark Gray", "Gray", "Green", "Light Gray", "Magenta",
17 "Orange", "Pink", "Red", "White", "Yellow" };
18
19 private Color colors[] = { Color.black, Color.blue,
20 Color.cyan, Color.darkGray, Color.gray, Color.green,
21 Color.lightGray, Color.magenta, Color.orange, Color.pink,
22 Color.red, Color.white, Color.yellow };
23
24 // set up GUI
25 public ListTest()
26 {
27 super( "List Test" );
28
29 // get content pane and set its layout
30 container = getContentPane();
31 container.setLayout( new FlowLayout() );
32
33 // create a list with items in colorNames array
34 colorList = new JList( colorNames );
35 colorList.setVisibleRowCount( 5 );
ListTest.java
Line 34
Use colorNames array to
populate JList
5
4
2002 Prentice Hall, Inc. All rights reserved.
Outline36 37 // do not allow multiple selections
38 colorList.setSelectionMode(
39 ListSelectionModel.SINGLE_SELECTION );
40
41 // add a JScrollPane containing JList to content pane
42 container.add( new JScrollPane( colorList ) );
43
44 // set up event handler
45 colorList.addListSelectionListener(
46
47 // anonymous inner class for list selection events
48 new ListSelectionListener() {
49
50 // handle list selection events
51 public void valueChanged( ListSelectionEvent event )
52 {
53 container.setBackground(
54 colors[ colorList.getSelectedIndex() ] );
55 }
56
57 } // end anonymous inner class
58
59 ); // end call to addListSelectionListener
60
61 setSize( 350, 150 );
62 setVisible( true );
63 }
64
65 // execute application
66 public static void main( String args[] )
67 {
68 ListTest application = new ListTest();
69
ListTest.java
Lines 38-39
Lines 45-59
Lines 51-55
Lines 53-54
JList allows single selections
Register JList to receive events from
anonymous ListSelectionListener
When user selects item in JList,
ListSelectionListener invokes
method valueChanged of all
registered listeners
Set appropriate background
depending on user selection
5
4
2002 Prentice Hall, Inc. All rights reserved.
Outline70 application.setDefaultCloseOperation(71 JFrame.EXIT_ON_CLOSE );
72 }
73
74 } // end class ListTest ListTest.java
5
4
Multiple-Selection Lists
Multiple-selection list
oChn nhiu mc trn Jlist
5
4
2002 Prentice Hall, Inc. All rights reserved.
Outline1 // Fig. 12.15: MultipleSelection.java
2 // Copying items from one List to another.
3
4 // Java core packages
5 import java.awt.*;
6 import java.awt.event.*;
7
8 // Java extension packages
9 import javax.swing.*;
10
11 public class MultipleSelection extends JFrame {
12 private JList colorList, copyList;
13 private JButton copyButton;
14
15 private String colorNames[] = { "Black", "Blue", "Cyan",
16 "Dark Gray", "Gray", "Green", "Light Gray",
17 "Magenta", "Orange", "Pink", "Red", "White", "Yellow" };
18
19 // set up GUI
20 public MultipleSelection()
21 {
22 super( "Multiple Selection Lists" );
23
24 // get content pane and set its layout
25 Container container = getContentPane();
26 container.setLayout( new FlowLayout() );
27
28 // set up JList colorList
29 colorList = new JList( colorNames );
30 colorList.setVisibleRowCount( 5 );
31 colorList.setFixedCellHeight( 15 );
32 colorList.setSelectionMode(
33 ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
34 container.add( new JScrollPane( colorList ) );
35
MultipleSelection.j
ava
Line 29
Lines 32-33
Use colorNames array to
populate JList
JList colorList allows
multiple selections
5
4
2002 Prentice Hall, Inc. All rights reserved.
Outline36 // create copy button and register its listener
37 copyButton = new JButton( "Copy >>>" );
38
39 copyButton.addActionListener(
40
41 // anonymous inner class for button event
42 new ActionListener() {
43
44 // handle button event
45 public void actionPerformed( ActionEvent event )
46 {
47 // place selected values in copyList
48 copyList.setListData(
49 colorList.getSelectedValues() );
50 }
51
52 } // end anonymous inner class
53
54 ); // end call to addActionListener
55
56 container.add( copyButton );
57
58 // set up JList copyList
59 copyList = new JList();
60 copyList.setVisibleRowCount( 5 );
61 copyList.setFixedCellWidth( 100 );
62 copyList.setFixedCellHeight( 15 );
63 copyList.setSelectionMode(
64 ListSelectionModel.SINGLE_INTERVAL_SELECTION );
65 container.add( new JScrollPane( copyList ) );
66
67 setSize( 300, 120 );
68 setVisible( true );
69 }
70
MultipleSelection.j
ava
Lines 48-49
Lines 63-64
When user presses JButton, JList
copyList adds items that user selected
from JList colorList
JList colorList
allows single selections
5
4
2002 Prentice Hall, Inc. All rights reserved.
Outline71 // execute application
72 public static void main( String args[] )
73 {
74 MultipleSelection application = new MultipleSelection();
75
76 application.setDefaultCloseOperation(
77 JFrame.EXIT_ON_CLOSE );
78 }
79
80 } // end class MultipleSelection
MultipleSelection.j
ava
5
4
Menus
Java cung cp mt s lp - JMenuBar, JMenu,
JMenuItem, JCheckBoxMenuItem, v
JRadioButtonMenuItem - thc thi menu trong
mt frame.
Mt JFrame hoc JApplet c th cha mt menu bar trn
c gn cc pull-down menu. Cc menu cha cc menu
item ngi dng la chn (hoc bt/tt). Menu bar c
th c xem nh mt cu trc h tr cc menu.
77
Menus (tt)
78
Lp JMenuBar
Menu bar cha cc menu; menu bar ch c th c thm vo 1 frame. on code sau to v thm mt JMenuBar
vo 1 frame:
JFrame f = new JFrame();
f.setSize(300, 200);
f.setVisible(true);
JMenuBar mb = new JMenuBar();
f.setJMenuBar(mb);
79
Lp JMenu
Gn cc menu vo mt JMenuBar. on code sau to 2 menu File v Help, v thm chng vo JMenuBar mb:
JMenu fileMenu = new JMenu("File", false);
JMenu helpMenu = new JMenu("Help", true);
mb.add(fileMenu);
mb.add(helpMenu);
80
Lp JMenuItem
on code sau thm cc mc chn (menu item) v cc separator trong menu fileMenu:
fileMenu.add(new JMenuItem("New"));
fileMenu.add(new JMenuItem("Open"));
fileMenu.addSeparator();
fileMenu.add(new JMenuItem("Print"));
fileMenu.addSeparator();
fileMenu.add(new JMenuItem("Exit"));
81
Menu Demo
82
Submenus
Thm cc submenus vo cc menu item. on code sau thm cc submenu Unix, NT, v Win95 vo trong mc chn Software.
JMenu softwareHelpSubMenu = new JMenu("Software");
JMenu hardwareHelpSubMenu = new JMenu("Hardware");
helpMenu.add(softwareHelpSubMenu);
helpMenu.add(hardwareHelpSubMenu);
softwareHelpSubMenu.add(new JMenuItem("Unix"));
softwareHelpSubMenu.add(new JMenuItem("NT"));
softwareHelpSubMenu.add(new JMenuItem("Win95"));
83
Submenu Demo
84