Page 1
1
Graphical User
Interfaces(POO 2009/2010)
Fernando Brito e Abreu ([email protected] )
Universidade Nova de Lisboa (http://www.unl.pt)QUASAR Research Group (http://ctp.di.fct.unl.pt/QUASAR)
15-04-2010
Chapter Goals
To understand the Java event model
To use inheritance to customize frames
To understand how user-interface
components are added to a container
To understand the use of layout managers
to arrange user-interface components in a
container
Continued…
Page 2
2
15-04-2010
Chapter Goals
To become familiar with common user-
interface components, such as buttons,
combo boxes, text areas, and menus
To build programs that handle events from
user-interface components
To install action and mouse event listeners
To accept input from buttons, text fields,
keyboard and mouse
15-04-2010
Where can I find this chapter?
Chapters 12 & 14
Chapter 18
(electronic chapter)
Page 3
3
15-04-2010
Events, Sources, and Listeners
User interface events include key presses, mouse moves, button clicks, and so on
Most programs don't want to be flooded by boring events
A program can indicate that it only cares about certain specific events
Continued…
15-04-2010
Events, Sources, and Listeners
Event listener: Notified when event happens
Belongs to a class that is provided by the application programmer
Its methods describe the actions to be taken when an event occurs
A program indicates which events it needs to receive by installing event listener objects
Page 4
4
15-04-2010
Events, Sources, and Listeners
Event source: Event sources include: keys, mouse,
buttons, joy sticks, timers moves, etc and so on
Event sources report on events
When an event occurs, the event source notifies all event listeners
15-04-2010
Events, Sources, and Listeners
Example: Use JButton components for buttons; attach an ActionListener to each button
ActionListener interface:
Need to supply a class whose actionPerformedmethod contains instructions to be executed when button is clicked
public interface ActionListener
{
void actionPerformed(ActionEvent event);
}
Page 5
5
15-04-2010
Events, Sources, and Listeners
event parameter contains details about the event, such as the time at which it occurred
Construct an object of the listener and add it to the button:
ActionListener listener = new ClickListener();
button.addActionListener(listener);
15-04-2010
File ClickListener.java
01: import java.awt.event.ActionEvent;
02: import java.awt.event.ActionListener;
03:
04: /**
05: An action listener that prints a message.
06: */
07: public class ClickListener implements ActionListener
08: {
09: public void actionPerformed(ActionEvent event)
10: {
11: System.out.println("I was clicked.");
12: }
13: }
Page 6
6
15-04-2010
File ButtonTester.java
01: import java.awt.event.ActionListener;
02: import javax.swing.JButton;
03: import javax.swing.JFrame;
04:
05: /**
06: This program demonstrates how to install an action listener.
07: */
08: public class ButtonTester
09: {
10: public static void main(String[] args)
11: {
12: JFrame frame = new JFrame();
13: JButton button = new JButton("Click me!");
14: frame.add(button);
15: Continued…
15-04-2010
File ClickListener.java
16: ActionListener listener = new ClickListener();
17: button.addActionListener(listener);
18:
19: frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
20: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
21: frame.setVisible(true);
22: }
23:
24: private static final int FRAME_WIDTH = 100;
25: private static final int FRAME_HEIGHT = 60;
26: }
Page 7
7
15-04-2010
File ClickListener.java
Figure 1:
Implementing an Action Listener
Output:
JButton
15-04-2010
Visual Programming
Some IDEs (e.g. Sun’s NetBeans) allow
building GUIs interactively, generating code
“behind the scenes”
However you, as an engineer, must:
Understand and be able to modify the
generated code
Understand the generation process (software
engineers are the authors of those tools too!)
Beware of limiting the portability of your code
across IDEs (e.g. Sun might disappear …)
Page 8
8
15-04-2010
Visual
Programming
1815-04-2010
Building Applications With Buttons
Example: investment viewer program;
whenever button is clicked, interest is
added, and new balance is displayed
Continued…
JButtonJLabel
Page 9
9
15-04-2010
Building Applications With Buttons
Construct an object of the JButton class:
We need a user interface component that
displays a message:
Continued…
JButton button = new JButton("Add Interest");
JLabel label = new JLabel("balance=" + account.getBalance());
15-04-2010
Building Applications With Buttons
Use a JPanel container to group multiple
user interface components together:
JPanel panel = new JPanel();
panel.add(button);
panel.add(label);
frame.add(panel);
JLabelJButton
Page 10
10
15-04-2010
Building Applications With Buttons
Listener class adds interest and displays
the new balance:
class AddInterestListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
double interest = account.getBalance() * INTEREST_RATE / 100;
account.deposit(interest);
label.setText("balance=" + account.getBalance());
}
}
Continued…
15-04-2010
Building Applications With Buttons
Add AddInterestListener as inner
class so it can have access to surrounding final variables (account and label)
Page 11
11
15-04-2010
File InvestmentViewer1.java
01: import java.awt.event.ActionEvent;
02: import java.awt.event.ActionListener;
03: import javax.swing.JButton;
04: import javax.swing.JFrame;
05: import javax.swing.JLabel;
06: import javax.swing.JPanel;
07: import javax.swing.JTextField;
08:
09: /**
10: This program displays the growth of an investment.
11: */
12: public class InvestmentViewer1
13: {
14: public static void main(String[] args)
15: {
16: JFrame frame = new JFrame();
17: Continued…
15-04-2010
File InvestmentViewer1.java
18: // The button to trigger the calculation
19: JButton button = new JButton("Add Interest");
20:
21: // The application adds interest to this bank account
22: final BankAccount account
= new BankAccount(INITIAL_BALANCE);
23:
24: // The label for displaying the results
25: final JLabel label = new JLabel(
26: "balance=" + account.getBalance());
27:
28: // The panel that holds the user interface components
29: JPanel panel = new JPanel();
30: panel.add(button);
31: panel.add(label);
32: frame.add(panel);
33:Continued…
Page 12
12
15-04-2010
File InvestmentViewer1.java
34: class AddInterestListener implements ActionListener
35: {
36: public void actionPerformed(ActionEvent event)
37: {
38: double interest = account.getBalance()
39: * INTEREST_RATE / 100;
40: account.deposit(interest);
41: label.setText(
42: "balance=" + account.getBalance());
43: }
44: }
45:
46: ActionListener listener = new AddInterestListener();
47: button.addActionListener(listener);
48:
49: frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
50: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
51: frame.setVisible(true);
52: } Continued…
15-04-2010
File InvestmentViewer1.java
53:
54: private static final double INTEREST_RATE = 10;
55: private static final double INITIAL_BALANCE = 1000;
56:
57: private static final int FRAME_WIDTH = 400;
58: private static final int FRAME_HEIGHT = 100;
59: }
Page 13
13
15-04-2010
Processing Text Input
Use JTextField components to provide
space for user input
Place a JLabel next to each text field
Supply a button that the user can press to
indicate that the input is ready for processing Continued…
final int FIELD_WIDTH = 10; // In characters
final JTextField rateField = new JTextField(FIELD_WIDTH);
JLabel rateLabel = new JLabel("Interest Rate: ");
15-04-2010
Processing Text Input
Continued…
JLabel JTextField JButton JLabel
Example. An investment viewer program similar to
the previous one, but where you can enter an interest
rate of your choice; whenever a button is clicked,
interest is added, and new balance is displayed
Page 14
14
15-04-2010
Processing Text Input
The button's actionPerformed method
reads the user input from the text fields (use getText)
class AddInterestListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
double rate = Double.parseDouble(rateField.getText());
. . .
}
}
15-04-2010
File InvestmentViewer2.java
01: import java.awt.event.ActionEvent;
02: import java.awt.event.ActionListener;
03: import javax.swing.JButton;
04: import javax.swing.JFrame;
05: import javax.swing.JLabel;
06: import javax.swing.JPanel;
07: import javax.swing.JTextField;
08:
09: /**
10: This program displays the growth of an investment.
11: */
12: public class InvestmentViewer2
13: {
14: public static void main(String[] args)
15: {
16: JFrame frame = new JFrame();
17: Continued…
Page 15
15
15-04-2010
File InvestmentViewer2.java18: // The label and text field for entering the
//interest rate
19: JLabel rateLabel = new JLabel("Interest Rate: ");
20:
21: final int FIELD_WIDTH = 10;
22: final JTextField rateField
= new JTextField(FIELD_WIDTH);
23: rateField.setText("" + DEFAULT_RATE);
24:
25: // The button to trigger the calculation
26: JButton button = new JButton("Add Interest");
27:
28: // The application adds interest to this bank account
29: final BankAccount account
= new BankAccount(INITIAL_BALANCE);
30:
31: // The label for displaying the results
32: final JLabel resultLabel = new JLabel(
33: "balance=" + account.getBalance());
34: Continued…
15-04-2010
File InvestmentViewer2.java
35: // The panel that holds the user interface components
36: JPanel panel = new JPanel();
37: panel.add(rateLabel);
38: panel.add(rateField);
39: panel.add(button);
40: panel.add(resultLabel);
41: frame.add(panel);
42:
43: class AddInterestListener implements ActionListener
44: {
45: public void actionPerformed(ActionEvent event)
46: {
47: double rate = Double.parseDouble(
48: rateField.getText());
49: double interest = account.getBalance()
50: * rate / 100;
51: account.deposit(interest); Continued…
Page 16
16
15-04-2010
File InvestmentViewer2.java52: resultLabel.setText(
53: "balance=" + account.getBalance());
54: }
55: }
56:
57: ActionListener listener = new AddInterestListener();
58: button.addActionListener(listener);
59:
60: frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
61: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
62: frame.setVisible(true);
63: }
64:
65: private static final double DEFAULT_RATE = 10;
66: private static final double INITIAL_BALANCE = 1000;
67:
68: private static final int FRAME_WIDTH = 500;
69: private static final int FRAME_HEIGHT = 200;
70: }
15-04-2010
Using Inheritance to Customize Frames
Use inheritance for complex frames to make
programs easier to understand
Design a subclass of JFrame
Store the components as instance fields
Initialize them in the constructor of your
subclass
If initialization code gets complex, simply
add some helper methods
Page 17
17
15-04-2010
Example: Investment Viewer Program
01: import java.awt.event.ActionEvent;
02: import java.awt.event.ActionListener;
03: import javax.swing.JButton;
04: import javax.swing.JFrame;
05: import javax.swing.JLabel;
06: import javax.swing.JPanel;
07: import javax.swing.JTextField;
08:
09: /**
10: This program displays the growth of an investment.
11: */
12: public class InvestmentFrame extends JFrame
13: {
14: public InvestmentFrame()
15: {
16: account = new BankAccount(INITIAL_BALANCE);
17:Continued…
15-04-2010
Example: Investment Viewer Program
18: // Use instance fields for components
19: resultLabel = new JLabel(
20: "balance=" + account.getBalance());
21:
22: // Use helper methods
23: createRateField();
24: createButton();
25: createPanel();
26:
27: setSize(FRAME_WIDTH, FRAME_HEIGHT);
28: }
29:
30: public void createRateField()
31: {
32: rateLabel = new JLabel("Interest Rate: ");
33: final int FIELD_WIDTH = 10;
34: rateField = new JTextField(FIELD_WIDTH); Continued…
Page 18
18
15-04-2010
Example: Investment Viewer Program
35: rateField.setText("" + DEFAULT_RATE);
36: }
37:
38: public void createButton()
39: {
40: button = new JButton("Add Interest");
41:
42: class AddInterestListener implements ActionListener
43: {
44: public void actionPerformed(ActionEvent event)
45: {
46: double rate = Double.parseDouble(
47: rateField.getText());
48: double interest = account.getBalance()
49: * rate / 100;
50: account.deposit(interest);
51: resultLabel.setText(
52: "balance=" + account.getBalance());
Continued…
15-04-2010
Example: Investment Viewer Program
53: }
54: }
55:
56: ActionListener listener = new AddInterestListener();
57: button.addActionListener(listener);
58: }
59:
60: public void createPanel()
61: {
62: JPanel panel = new JPanel();
63: panel.add(rateLabel);
64: panel.add(rateField);
65: panel.add(button);
66: panel.add(resultLabel);
67: add(panel);
68: }
69: Continued…
Page 19
19
15-04-2010
Example: Investment Viewer Program
70: private JLabel rateLabel;
71: private JTextField rateField;
72: private JButton button;
73: private JLabel resultLabel;
74: private BankAccount account;
75:
76: private static final double DEFAULT_RATE = 10;
77: private static final double INITIAL_BALANCE = 1000;
78:
79: private static final int FRAME_WIDTH = 500;
80: private static final int FRAME_HEIGHT = 200;
81: }
15-04-2010
Example: Investment Viewer Program
01: import javax.swing.JFrame;
02:
03: /**
04: This program tests the InvestmentFrame.
05: */
06: public class InvestmentFrameViewer
07: {
08: public static void main(String[] args)
09: {
10: JFrame frame = new InvestmentFrame();
11: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
12: frame.setVisible(true);
13: }
14: }
15:
Of course, we still need a class with a main method:
Page 20
20
15-04-2010
Layout Management
Up to now, we have had limited control
over the of components
When we used a panel, it arranged the
components from the left to the right
User-interface components are arranged
by placing them inside containers
Continued…
15-04-2010
Layout Management
Each container has a layout manager that
directs the arrangement of its components
Three useful layout managers:
flow layout (default)
border layout
grid layout
Page 21
21
15-04-2010
Layout Management
By default, JPanel places components
from left to right and starts a new row when
needed
Panel layout carried out by FlowLayout
layout manager
Can set other layout managers
panel.setLayout(new BorderLayout());
15-04-2010
Border Layout
Border layout groups container into five
areas: center, north, west, south and east
Continued…
Page 22
22
15-04-2010
Border Layout
Default layout manager for a frame
(technically, the frame's content pane)
When adding a component, specify the
position like this:
Expands each component to fill the entire
allotted area
If that is not desirable, place each
component inside a panel
panel.add(component, BorderLayout.NORTH);
15-04-2010
Grid Layout
Arranges components in a grid with a fixed
number of rows and columns
Resizes each component so that they all
have same size
Expands each component to fill the entire
allotted area
Page 23
23
15-04-2010
Grid Layout
Add the components, row by row, left to
right:
JPanel numberPanel = new JPanel();
numberPanel.setLayout(new GridLayout(4, 3));
numberPanel.add(button7);
numberPanel.add(button8);
numberPanel.add(button9);
numberPanel.add(button4);
. . .
15-04-2010
Grid Bag Layout
Tabular arrangement of components
Columns can have different sizes
Components can span multiple columns
Quite complex to use
Not covered in the book
Continued…
Page 24
24
15-04-2010
Grid Bag Layout
Fortunately, you can create acceptable-
looking layouts by nesting panels
Give each panel an appropriate layout
manager
Panels don’t have visible borders
Use as many panels as needed to organize
components
15-04-2010
Choices
Radio buttons
Check boxes
Combo boxes
Page 25
25
15-04-2010
Radio Buttons
For a small set of mutually exclusive
choices, use radio buttons or a combo box
In a radio button set, only one button can
be selected at a time
When a button is selected, previously
selected button in set is automatically
turned off
15-04-2010
Radio Buttons
In previous figure, font sizes are mutually
exclusive:
JRadioButton smallButton = new JRadioButton("Small");
JRadioButton mediumButton = new JRadioButton("Medium");
JRadioButton largeButton = new JRadioButton("Large");
// Add radio buttons into a ButtonGroup so that
// only one button in group is on at any time
ButtonGroup group = new ButtonGroup();
group.add(smallButton);
group.add(mediumButton);
group.add(largeButton);
Page 26
26
15-04-2010
Radio Buttons
Button group does not place buttons close to
each other on container
It is your job to arrange buttons on screen
isSelected: called to find out if a button is
currently selected or not
Call setSelected(true) on a radio button in
group before making the enclosing frame visible
if(largeButton.isSelected()) size = LARGE_SIZE;
15-04-2010
Borders
Place a border around a panel to group its
contents visually
EtchedBorder: theree-dimensional
etched effect
Can add a border to any component, but
most commonly to panels:
Jpanel panel = new JPanel ();
panel.setBorder(new EtchedBorder ());
Continued…
Page 27
27
15-04-2010
Borders
TitledBorder: a border with a title
Panel.setBorder(new TitledBorder(new EtchedBorder(), “Size”));
15-04-2010
Check Boxes
Two states: checked and unchecked
Use one checkbox for a binary choice
Use a group of check boxes when one
selection does not exclude another
Example: "bold" and "italic" in previous
figure
Continued…
Page 28
28
15-04-2010
Check Boxes
Construct by giving the name in the constructor:
Don't place into a button group
isSelected: called to find out if a check box is currently selected or not
To define default value on a check box setSelected(true)
setSelected(false)
JCheckBox italicCheckBox = new JCheckBox("Italic");
if(italicCheckBox.isSelected()) …
15-04-2010
Combo Boxes
For a large set of choices, use a combo box
Uses less space than radio buttons
"Combo": combination of a list and a text
field
The text field displays the name of the current
selection
Continued…
Page 29
29
15-04-2010
Combo Boxes
If combo box is editable, user can type own
selection
Use setEditable method
Add strings with addItem method:
JComboBox facenameCombo = new JComboBox();
facenameCombo.addItem("Serif");
facenameCombo.addItem("SansSerif");
facenameCombo.addItem("Monospaced");
Continued…
15-04-2010
Combo Boxes
Get user selection with getSelectedItem
(return type is Object)
Select an item with setSelectedItem
This is useful for setting the default option
(remember the pain of finding your country
within all countries in the world )
String selectedString =
(String) facenameCombo.getSelectedItem();
Page 30
30
15-04-2010
Radio Buttons, Check Boxes,
and Combo Boxes
They generate an ActionEvent
whenever the user selects an item
Continued…
15-04-2010
Radio Buttons, Check Boxes, and
Combo Boxes An example: ChoiceFrame
Figure 5:
The Components of
the Choice Frame
Continued…
Page 31
31
15-04-2010
Radio Buttons, Check Boxes, and
Combo Boxes
All components notify the same listener object
When user clicks on any component, we ask
each component for its current content
Then redraw text sample with the new font
15-04-2010
Classes of the Font Choice Program
Page 32
32
15-04-2010
File ChoiceFrameViewer.java
01: import javax.swing.JFrame;
02:
03: /**
04: This program tests the ChoiceFrame.
05: */
06: public class ChoiceFrameViewer
07: {
08: public static void main(String[] args)
09: {
10: JFrame frame = new ChoiceFrame();
11: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
12: frame.setVisible(true);
13: }
14: }
15:
15-04-2010
File ChoiceFrame.java
001: import java.awt.BorderLayout;
002: import java.awt.Font;
003: import java.awt.GridLayout;
004: import java.awt.event.ActionEvent;
005: import java.awt.event.ActionListener;
006: import javax.swing.ButtonGroup;
007: import javax.swing.JButton;
008: import javax.swing.JCheckBox;
009: import javax.swing.JComboBox;
010: import javax.swing.JFrame;
011: import javax.swing.JLabel;
012: import javax.swing.JPanel;
013: import javax.swing.JRadioButton;
014: import javax.swing.border.EtchedBorder;
015: import javax.swing.border.TitledBorder;
016:Continued…
Page 33
33
15-04-2010
File ChoiceFrame.java
017: /**
018: This frame contains a text field and a control panel
019: to change the font of the text.
020: */
021: public class ChoiceFrame extends JFrame
022: {
023: /**
024: Constructs the frame.
025: */
026: public ChoiceFrame()
027: {
028: // Construct text sample
029: sampleField = new JLabel("Big Java");
030: add(sampleField, BorderLayout.CENTER);
031: Continued…
15-04-2010
File ChoiceFrame.java
032: // This listener is shared among all components
033: class ChoiceListener implements ActionListener
034: {
035: public void actionPerformed(ActionEvent event)
036: {
037: setSampleFont();
038: }
039: }
040:
041: listener = new ChoiceListener();
042:
043: createControlPanel();
044: setSampleFont();
045: setSize(FRAME_WIDTH, FRAME_HEIGHT);
046: }
047: Continued…
Page 34
34
15-04-2010
File ChoiceFrame.java
048: /**
049: Creates the control panel to change the font.
050: */
051: public void createControlPanel()
052: {
053: JPanel facenamePanel = createComboBox();
054: JPanel sizeGroupPanel = createCheckBoxes();
055: JPanel styleGroupPanel = createRadioButtons();
056:
057: // Line up component panels
058:
059: JPanel controlPanel = new JPanel();
060: controlPanel.setLayout(new GridLayout(3, 1));
061: controlPanel.add(facenamePanel);
062: controlPanel.add(sizeGroupPanel);
063: controlPanel.add(styleGroupPanel);
064: Continued…
15-04-2010
File ChoiceFrame.java065: // Add panels to content pane
066:
067: add(controlPanel, BorderLayout.SOUTH);
068: }
069:
070: /**
071: Creates the combo box with the font style choices.
072: @return the panel containing the combo box
073: */
074: public JPanel createComboBox()
075: {
076: facenameCombo = new JComboBox();
077: facenameCombo.addItem("Serif");
078: facenameCombo.addItem("SansSerif");
079: facenameCombo.addItem("Monospaced");
080: facenameCombo.setEditable(true);
081: facenameCombo.addActionListener(listener);
082:
Continued…
Page 35
35
15-04-2010
File ChoiceFrame.java
083: JPanel panel = new JPanel();
084: panel.add(facenameCombo);
085: return panel;
086: }
087:
088: /**
089: Creates the check boxes for selecting bold and
// italic styles.
090: @return the panel containing the check boxes
091: */
092: public JPanel createCheckBoxes()
093: {
094: italicCheckBox = new JCheckBox("Italic");
095: italicCheckBox.addActionListener(listener);
096:
097: boldCheckBox = new JCheckBox("Bold");
098: boldCheckBox.addActionListener(listener);
099: Continued…
15-04-2010
File ChoiceFrame.java
100: JPanel panel = new JPanel();
101: panel.add(italicCheckBox);
102: panel.add(boldCheckBox);
103: panel.setBorder
104: (new TitledBorder(new EtchedBorder(), "Style"));
105:
106: return panel;
107: }
108:
109: /**
110: Creates the radio buttons to select the font size
111: @return the panel containing the radio buttons
112: */
113: public JPanel createRadioButtons()
114: {
115: smallButton = new JRadioButton("Small");
116: smallButton.addActionListener(listener); Continued…
Page 36
36
15-04-2010
File ChoiceFrame.java
117:
118: mediumButton = new JRadioButton("Medium");
119: mediumButton.addActionListener(listener);
120:
121: largeButton = new JRadioButton("Large");
122: largeButton.addActionListener(listener);
123: largeButton.setSelected(true);
124:
125: // Add radio buttons to button group
126:
127: ButtonGroup group = new ButtonGroup();
128: group.add(smallButton);
129: group.add(mediumButton);
130: group.add(largeButton);
131: Continued…
15-04-2010
File ChoiceFrame.java
132: JPanel panel = new JPanel();
133: panel.add(smallButton);
134: panel.add(mediumButton);
135: panel.add(largeButton);
136: panel.setBorder
137: (new TitledBorder(new EtchedBorder(), "Size"));
138:
139: return panel;
140: }
141:
142: /**
143: Gets user choice for font name, style, and size
144: and sets the font of the text sample.
145: */
146: public void setSampleFont()
147: { Continued…
Page 37
37
15-04-2010
File ChoiceFrame.java
148: // Get font name
149: String facename
150: = (String) facenameCombo.getSelectedItem();
151:
152: // Get font style
153:
154: int style = 0;
155: if (italicCheckBox.isSelected())
156: style = style + Font.ITALIC;
157: if (boldCheckBox.isSelected())
158: style = style + Font.BOLD;
159:
160: // Get font size
161:
162: int size = 0;
163: Continued…
15-04-2010
File ChoiceFrame.java
164: final int SMALL_SIZE = 24;
165: final int MEDIUM_SIZE = 36;
166: final int LARGE_SIZE = 48;
167:
168: if (smallButton.isSelected())
169: size = SMALL_SIZE;
170: else if (mediumButton.isSelected())
171: size = MEDIUM_SIZE;
172: else if (largeButton.isSelected())
173: size = LARGE_SIZE;
174:
175: // Set font of text field
176:
177: sampleField.setFont(new Font(facename, style, size));
178: sampleField.repaint();
179: } Continued…
Page 38
38
15-04-2010
File ChoiceFrame.java
180:
181: private JLabel sampleField;
182: private JCheckBox italicCheckBox;
183: private JCheckBox boldCheckBox;
184: private JRadioButton smallButton;
185: private JRadioButton mediumButton;
186: private JRadioButton largeButton;
187: private JComboBox facenameCombo;
188: private ActionListener listener;
189:
190: private static final int FRAME_WIDTH = 300;
191: private static final int FRAME_HEIGHT = 400;
192: } Continued…
15-04-2010
Advanced Topic: Layout Management
Step 1: Make a sketch of your desired
component layout
Page 39
39
15-04-2010
Advanced Topic: Layout Management
Step 2: Find groupings of adjacent
components with the same layout
15-04-2010
Advanced Topic: Layout Management
Step 3: Identify layouts for each group
Step 4: Group the groups together
Step 5: Write the code to generate the layout
Page 40
40
15-04-2010
Menus
A frame contains a menu bar
The menu bar contains menus
A menu contains submenus and menu
items
15-04-2010
Menus
Figure 7:
Pull-Down Menus
public class MenuFrame extends JFrame
{
…
public MenuFrame()
{
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
menuBar.add(createFileMenu());
menuBar.add(createFontMenu());
…
Page 41
41
15-04-2010
Menu Items
Add menu items & submenus with the add method:
A menu item has no further submenus
Menu items generate action events
JMenu fileMenu = new JMenu(“File”);
JMenuItem fileExitItem = new JMenuItem("Exit");
fileMenu.add(fileExitItem);
JMenu fileSendToSubmenu = new JMenu(“File Send”);
JMenuItem sendToMyDocsItem = new JMenuItem(“Send To MyDocs");
JMenuItem sendToMailItem = new JMenuItem(“Send To Mail");
fileSendToSubmenu.add(sendToMyDocsItem);
fileSendToSubmenu.add(sendToMailItem);
fileMenu.add(fileSendToSubmenu);
Continued…
15-04-2010
Menu Items
Add a listener to each menu item:
Add action listeners only to menu items, not to menus or the menu bar
fileExitItem.addActionListener(fileExitlistener);
sendToMyDocsItem.addActionListener(sendToMyDocsListener);
sendToMailItem.addActionListener(sendToMailListener);
Page 42
42
15-04-2010
A Sample Program
Builds up a small but typical menu
Traps action events from menu items
To keep program readable, use a separate
method for each menu or set of related
menus
createFaceItem: creates menu item to
change the font face
createSizeItem
createStyleItem
15-04-2010
File MenuFrameViewer.java
01: import javax.swing.JFrame;
02:
03: /**
04: This program tests the MenuFrame.
05: */
06: public class MenuFrameViewer
07: {
08: public static void main(String[] args)
09: {
10: JFrame frame = new MenuFrame();
11: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
12: frame.setVisible(true);
13: }
14: }
15:
Page 43
43
15-04-2010
File MenuFrame.java
001: import java.awt.BorderLayout;
002: import java.awt.Font;
003: import java.awt.GridLayout;
004: import java.awt.event.ActionEvent;
005: import java.awt.event.ActionListener;
006: import javax.swing.ButtonGroup;
007: import javax.swing.JButton;
008: import javax.swing.JCheckBox;
009: import javax.swing.JComboBox;
010: import javax.swing.JFrame;
011: import javax.swing.JLabel;
012: import javax.swing.JMenu;
013: import javax.swing.JMenuBar;
014: import javax.swing.JMenuItem;
015: import javax.swing.JPanel;
016: import javax.swing.JRadioButton; Continued…
15-04-2010
File MenuFrame.java
017: import javax.swing.border.EtchedBorder;
018: import javax.swing.border.TitledBorder;
019:
020: /**
021: This frame has a menu with commands to change the font
022: of a text sample.
023: */
024: public class MenuFrame extends JFrame
025: {
026: /**
027: Constructs the frame.
028: */
029: public MenuFrame()
030: {
031: // Construct text sample
032: sampleField = new JLabel("Big Java");
033: add(sampleField, BorderLayout.CENTER);
034: Continued…
Page 44
44
15-04-2010
File MenuFrame.java
035: // Construct menu
036: JMenuBar menuBar = new JMenuBar();
037: setJMenuBar(menuBar);
038: menuBar.add(createFileMenu());
039: menuBar.add(createFontMenu());
040:
041: facename = "Serif";
042: fontsize = 24;
043: fontstyle = Font.PLAIN;
044:
045: setSampleFont();
046: setSize(FRAME_WIDTH, FRAME_HEIGHT);
047: }
048:
049: /**
050: Creates the File menu.
051: @return the menu
052: */ Continued…
15-04-2010
File MenuFrame.java
053: public JMenu createFileMenu()
054: {
055: JMenu menu = new JMenu("File");
056: menu.add(createFileExitItem());
057: return menu;
058: }
059:
060: /**
061: Creates the File->Exit menu item and sets its
// action listener.
062: @return the menu item
063: */
064: public JMenuItem createFileExitItem()
065: {
066: JMenuItem item = new JMenuItem("Exit");
067: class MenuItemListener implements ActionListener
068: {
069: public void actionPerformed(ActionEvent event)
Continued…
Page 45
45
15-04-2010
File MenuFrame.java
070: {
071: System.exit(0);
072: }
073: }
074: ActionListener listener = new MenuItemListener();
075: item.addActionListener(listener);
076: return item;
077: }
078:
079: /**
080: Creates the Font submenu.
081: @return the menu
082: */
083: public JMenu createFontMenu()
084: {
085: JMenu menu = new JMenu("Font");
086: menu.add(createFaceMenu()); Continued…
15-04-2010
File MenuFrame.java
087: menu.add(createSizeMenu());
088: menu.add(createStyleMenu());
089: return menu;
090: }
091:
092: /**
093: Creates the Face submenu.
094: @return the menu
095: */
096: public JMenu createFaceMenu()
097: {
098: JMenu menu = new JMenu("Face");
099: menu.add(createFaceItem("Serif"));
100: menu.add(createFaceItem("SansSerif"));
101: menu.add(createFaceItem("Monospaced"));
102: return menu;
103: }
104: Continued…
Page 46
46
15-04-2010
File MenuFrame.java
105: /**
106: Creates the Size submenu.
107: @return the menu
108: */
109: public JMenu createSizeMenu()
110: {
111: JMenu menu = new JMenu("Size");
112: menu.add(createSizeItem("Smaller", -1));
113: menu.add(createSizeItem("Larger", 1));
114: return menu;
115: }
116:
117: /**
118: Creates the Style submenu.
119: @return the menu
120: */
121: public JMenu createStyleMenu()
122: { Continued…
15-04-2010
File MenuFrame.java
123: JMenu menu = new JMenu("Style");
124: menu.add(createStyleItem("Plain", Font.PLAIN));
125: menu.add(createStyleItem("Bold", Font.BOLD));
126: menu.add(createStyleItem("Italic", Font.ITALIC));
127: menu.add(createStyleItem("Bold Italic", Font.BOLD
128: + Font.ITALIC));
129: return menu;
130: }
131:
132:
133: /**
134: Creates a menu item to change the font face and
// set its action listener.
135: @param name the name of the font face
136: @return the menu item
137: */
138: public JMenuItem createFaceItem(final String name)
139: { Continued…
Page 47
47
15-04-2010
File MenuFrame.java
140: JMenuItem item = new JMenuItem(name);
141: class MenuItemListener implements ActionListener
142: {
143: public void actionPerformed(ActionEvent event)
144: {
145: facename = name;
146: setSampleFont();
147: }
148: }
149: ActionListener listener = new MenuItemListener();
150: item.addActionListener(listener);
151: return item;
152: }
153: Continued…
15-04-2010
File MenuFrame.java
154: /**
155: Creates a menu item to change the font size
156: and set its action listener.
157: @param name the name of the menu item
158: @param ds the amount by which to change the size
159: @return the menu item
160: */
161: public JMenuItem createSizeItem(String name, final int ds)
162: {
163: JMenuItem item = new JMenuItem(name);
164: class MenuItemListener implements ActionListener
165: {
166: public void actionPerformed(ActionEvent event)
167: {
168: fontsize = fontsize + ds;
169: setSampleFont();
170: }
171: } Continued…
Page 48
48
15-04-2010
File MenuFrame.java
172: ActionListener listener = new MenuItemListener();
173: item.addActionListener(listener);
174: return item;
175: }
176:
177: /**
178: Creates a menu item to change the font style
179: and set its action listener.
180: @param name the name of the menu item
181: @param style the new font style
182: @return the menu item
183: */
184: public JMenuItem createStyleItem(String name,
final int style)
185: {
186: JMenuItem item = new JMenuItem(name);
187: class MenuItemListener implements ActionListener
188: { Continued…
15-04-2010
File MenuFrame.java
189: public void actionPerformed(ActionEvent event)
190: {
191: fontstyle = style;
192: setSampleFont();
193: }
194: }
195: ActionListener listener = new MenuItemListener();
196: item.addActionListener(listener);
197: return item;
198: }
199:
200: /**
201: Sets the font of the text sample.
202: */
203: public void setSampleFont()
204: { Continued…
Page 49
49
15-04-2010
File MenuFrame.java
205: Font f = new Font(facename, fontstyle, fontsize);
206: sampleField.setFont(f);
207: sampleField.repaint();
208: }
209:
210: private JLabel sampleField;
211: private String facename;
212: private int fontstyle;
213: private int fontsize;
214:
215: private static final int FRAME_WIDTH = 300;
216: private static final int FRAME_HEIGHT = 400;
217: }
218:
219:
15-04-2010
Text Areas
Use a JTextArea to show multiple lines of text
You can specify the number of rows and
columns:
setText: to set the text of a text field or text
area
append: to add text to the end of a text area
final int ROWS = 10;
final int COLUMNS = 30;
JTextArea textArea = new JTextArea(ROWS, COLUMNS);
Continued…
Page 50
50
15-04-2010
Text Areas
Use newline characters to separate lines:
To use for display purposes only:
textArea.append(account.getBalance() + "\n");
textArea.setEditable(false);
// program can call setText and append to change it
15-04-2010
Text Areas
To add scroll bars to a text area:
Continued…
JTextArea textArea = new JTextArea(ROWS, COLUMNS);
JScrollPane scrollPane = new JScrollPane(textArea);
Page 51
51
15-04-2010
Text Areas
Figure 8:The TextAreaViewerApplication
15-04-2010
File TextAreaViewer.java
01: import java.awt.BorderLayout;
02: import java.awt.event.ActionEvent;
03: import java.awt.event.ActionListener;
04: import javax.swing.JButton;
05: import javax.swing.JFrame;
06: import javax.swing.JLabel;
07: import javax.swing.JPanel;
08: import javax.swing.JScrollPane;
09: import javax.swing.JTextArea;
10: import javax.swing.JTextField;
11:
12: /**
13: This program shows a frame with a text area that
14: displays the growth of an investment.
15: */
16: public class TextAreaViewer
17: {
Continued…
Page 52
52
15-04-2010
File TextAreaViewer.java18: public static void main(String[] args)
19: {
20: JFrame frame = new JFrame();
21:
22: // The application adds interest to this bank account
23: final BankAccount account =
new BankAccount(INITIAL_BALANCE);
24: // The text area for displaying the results
25: final int AREA_ROWS = 10;
26: final int AREA_COLUMNS = 30;
27:
28: final JTextArea textArea = new JTextArea(
29: AREA_ROWS, AREA_COLUMNS);
30: textArea.setEditable(false);
31: JScrollPane scrollPane = new JScrollPane(textArea);
32:
33: // The label and text field for entering the
// interest rate
Continued…
15-04-2010
File TextAreaViewer.java34: JLabel rateLabel = new JLabel("Interest Rate: ");
35:
36: final int FIELD_WIDTH = 10;
37: final JTextField rateField =
new JTextField(FIELD_WIDTH);
38: rateField.setText("" + DEFAULT_RATE);
39:
40: // The button to trigger the calculation
41: JButton calculateButton = new JButton("Add Interest");
42:
43: // The panel that holds the input components
44: JPanel northPanel = new JPanel();
45: northPanel.add(rateLabel);
46: northPanel.add(rateField);
47: northPanel.add(calculateButton);
48:
49: frame.add(northPanel, BorderLayout.NORTH);
50: frame.add(scrollPane);
51: Continued…
Page 53
53
15-04-2010
File TextAreaViewer.java
52: class CalculateListener implements ActionListener
53: {
54: public void actionPerformed(ActionEvent event)
55: {
56: double rate = Double.parseDouble(
57: rateField.getText());
58: double interest = account.getBalance()
59: * rate / 100;
60: account.deposit(interest);
61: textArea.append(account.getBalance() + "\n");
62: }
63: }
64:
65: ActionListener listener = new CalculateListener();
66: calculateButton.addActionListener(listener);
67:
Continued…
15-04-2010
File TextAreaViewer.java
68: frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
69: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
70: frame.setVisible(true);
71: }
72:
73: private static final double DEFAULT_RATE = 10;
74: private static final double INITIAL_BALANCE = 1000;
75:
76: private static final int FRAME_WIDTH = 400;
77: private static final int FRAME_HEIGHT = 200;
78: }
Page 54
54
15-04-2010
Exploring the Swing Documentation
For more sophisticated effects, explore the
Swing documentation
The documentation can be quite
intimidating at first glance
Next example will show how to use the
documentation to your advantage
15-04-2010
Example: A Color Mixer
It should be fun to
mix your own
colors, with a slider
for the red, green,
and blue values
Figure 9:
A Color Mixer
Page 55
55
15-04-2010
Example: A Color Mixer
How do you know if there is a slider?
Buy a book that illustrates all Swing
components
Run sample application included in the JDK
that shows off all Swing components
Look at the names of all of the classes that
start with J
JSlider seems like a good candidate
Continued…
15-04-2010
Example: A Color Mixer
Next, ask a few questions:
How do I construct a JSlider?
How can I get notified when the user has
moved it?
How can I tell to which value the user has set
it?
After mastering sliders, you can find out
how to set tick marks, etc.
Continued…
Page 56
56
15-04-2010
The Swing Demo Set
Figure 9:
The SwingSet Demo
15-04-2010
Example: A Color Mixer
There are over 50 methods in JSlider
class and over 250 inherited methods
Some method descriptions look scary
Continued…
Page 57
57
15-04-2010
Example: A Color Mixer
Develop the ability to separate fundamental
concepts from ephemeral minutiae
Figure 11: A Mysterious Method Description from the API Documentation
15-04-2010
How do I construct a JSlider?
Look at the Java version 5.0 API
documentation
There are six constructors for the JSlider
class
Learn about one or two of them
Strike a balance somewhere between the
trivial and the bizarre
Continued…
Page 58
58
15-04-2010
How do I construct a JSlider?
Imagine we want to create a horizontal slider with
the range 0 to 100 and an initial value of 50
This is too limited:
This is bizarre:
Creates a horizontal slider using the specified
BoundedRangeModel
public JSlider()
public JSlider(BoundedRangeModel brm)
Continued…
15-04-2010
How do I construct a JSlider?
Useful:
Creates a horizontal slider using the specified
min, max, and value
public JSlider(int min, int max, int value)
Page 59
59
15-04-2010
How Can I Get Notified When the User Has Moved a JSlider?
There is no addActionListener method
There is a method
Click on the ChangeListener link to find out that
this interface has a single method:
Continued…
public void addChangeListener(ChangeListener l)
void stateChanged(ChangeEvent e)
15-04-2010
How Can I Get Notified When the User Has Moved a JSlider?
Apparently, method is called whenever
user moves the slider
What is a ChangeEvent?
It inherits getSource method from
superclass EventObject
getSource: tells us which component
generated this event
Page 60
60
15-04-2010
How Can I Tell to Which Value the User Has Set a JSlider?
Now we have a plan:
Add a change event listener to each slider
When slider is changed, stateChanged
method is called
Find out the new value of the slider
Recompute color value
Repaint color panel
Continued…
15-04-2010
How Can I Tell to Which Value the User Has Set a JSlider?
Need to get the current value of the slider
Look at all the methods that start with get;
you find:
Returns the slider's value.
public int getValue()
Page 61
61
15-04-2010
The Components of the
SliderFrame
Figure 12:The Components of the SliderFrame
15-04-2010
Classes of the
SliderFrameViewer Program
Figure 13:Classes of the SliderFrameViewer Program
Page 62
62
15-04-2010
File SliderFrameViewer.java
01: import javax.swing.JFrame;
02:
03: public class SliderFrameViewer
04: {
05: public static void main(String[] args)
06: {
07: SliderFrame frame = new SliderFrame();
08: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
09: frame.setVisible(true);
10: }
11: }
12:
15-04-2010
File SliderFrame.java
01: import java.awt.BorderLayout;
02: import java.awt.Color;
03: import java.awt.GridLayout;
04: import javax.swing.JFrame;
05: import javax.swing.JLabel;
06: import javax.swing.JPanel;
07: import javax.swing.JSlider;
08: import javax.swing.event.ChangeListener;
09: import javax.swing.event.ChangeEvent;
10:
11: public class SliderFrame extends JFrame
12: {
13: public SliderFrame()
14: {
15: colorPanel = new JPanel();
16: Continued…
Page 63
63
15-04-2010
File SliderFrame.java
17: add(colorPanel, BorderLayout.CENTER);
18: createControlPanel();
19: setSampleColor();
20: setSize(FRAME_WIDTH, FRAME_HEIGHT);
21: }
22:
23: public void createControlPanel()
24: {
25: class ColorListener implements ChangeListener
26: {
27: public void stateChanged(ChangeEvent event)
28: {
29: setSampleColor();
30: }
31: }
32:Continued…
15-04-2010
File SliderFrame.java
33: ChangeListener listener = new ColorListener();
34:
35: redSlider = new JSlider(0, 100, 100);
36: redSlider.addChangeListener(listener);
37:
38: greenSlider = new JSlider(0, 100, 70);
39: greenSlider.addChangeListener(listener);
40:
41: blueSlider = new JSlider(0, 100, 70);
42: blueSlider.addChangeListener(listener);
43:
44: JPanel controlPanel = new JPanel();
45: controlPanel.setLayout(new GridLayout(3, 2));
46:
47: controlPanel.add(new JLabel("Red"));
48: controlPanel.add(redSlider);
49: Continued…
Page 64
64
15-04-2010
File SliderFrame.java
50: controlPanel.add(new JLabel("Green"));
51: controlPanel.add(greenSlider);
52:
53: controlPanel.add(new JLabel("Blue"));
54: controlPanel.add(blueSlider);
55:
56: add(controlPanel, BorderLayout.SOUTH);
57: }
58:
59: /**
60: Reads the slider values and sets the panel to
61: the selected color.
62: */
63: public void setSampleColor()
64: {
65: // Read slider values
66: Continued…
15-04-2010
File SliderFrame.java
67: float red = 0.01F * redSlider.getValue();
68: float green = 0.01F * greenSlider.getValue();
69: float blue = 0.01F * blueSlider.getValue();
70:
71: // Set panel background to selected color
72:
73: colorPanel.setBackground(new Color(red, green, blue));
74: colorPanel.repaint();
75: }
76:
77: private JPanel colorPanel;
78: private JSlider redSlider;
79: private JSlider greenSlider;
80: private JSlider blueSlider;
81:
82: private static final int FRAME_WIDTH = 300;
83: private static final int FRAME_HEIGHT = 400;
84: } Continued…
Page 65
65
15-04-2010
Keyboard Events
"Key typed" events are higher-level and generally
do not depend on the platform or keyboard layout
They are generated when a Unicode character is entered,
and are the preferred way to find out about character
input.
In the simplest case, a key typed event is produced by a
single key press (e.g., 'a'). Often, however, characters are
produced by series of key presses (e.g., 'shift' + 'a'), and
the mapping from key pressed events to key typed events
may be many-to-one or many-to-many.
15-04-2010
Keyboard Events Key releases are not usually necessary to generate a
key typed event, but there are some cases where the
key typed event is not generated until a key is
released
e.g., entering ASCII sequences via the Alt-Numpad method
in Windows)
No key typed events are generated for keys that
don't generate Unicode characters
e.g., action keys, modifier keys, etc.
Page 66
66
15-04-2010
Keyboard Events
"Key pressed" and "key released" events are
lower-level and depend on the platform and
keyboard layout
They are generated whenever a key is pressed or
released, and are the only way to find out about
keys that don't generate character input
e.g., action keys, modifier keys, etc.
The key being pressed or released is indicated by
the getKeyCode method, which returns a virtual
key code
15-04-2010
Keyboard Events
Virtual key codes are used to report which
keyboard key has been pressed, rather than a
character generated by the combination of one or
more keystrokes (such as "A", which comes from
shift and "a")
For example, pressing the Shift key will cause a
KEY_PRESSED event with a VK_SHIFT keyCode, while
pressing the 'a' key will result in a VK_A keyCode
After the 'a' key is released, a KEY_RELEASED event
will be fired with VK_A
Separately, a KEY_TYPED event with a keyChar value
of 'A' is generated
Page 67
67
15-04-2010
Keyboard interface
Continued…
public interface KeyListener
{
void keyTyped(KeyEvent event);
// Called when a key is typed
void keyPressed(KeyEvent event);
// Called when the key is pressed
void keyReleased(KeyEvent event);
// Called when the key is released
}
15-04-2010
KeyEvent methods
The getKeyChar method always returns a valid
Unicode character or CHAR_UNDEFINED
For key pressed and key released events, the
getKeyCode method returns the event's keyCode
For key typed events, the getKeyCode method
always returns VK_UNDEFINED
Page 68
68
15-04-2010
Handling keyboard events
Add a mouse listener to a component by calling the addMouseListener method:
Continued…
public class MyKeyboardListener implements KeyListener
{
// Implements the three methods
}
KeyListener listener = new MyKeyboardListener();
component.addKeyListener(listener);
15-04-2010
Mouse Events
mousePressed, mouseReleased: called
when a mouse button is pressed or released
mouseClicked: if button is pressed and
released in quick succession, and mouse
hasn't moved
mouseEntered, mouseExited: mouse
has entered or exited the component's area
mouseMoved, mouseDragged: mouse
moves and you can use (or not) its button
Page 69
69
15-04-2010
Mouse interfaces
Continued…
public interface MouseListener
{
void mousePressed(MouseEvent event);
// Called when a mouse button has been pressed on a component
void mouseReleased(MouseEvent event);
// Called when a mouse button has been released on a component
void mouseClicked(MouseEvent event);
// Called when the mouse has been clicked on a component
void mouseEntered(MouseEvent event);
// Called when the mouse enters a component
void mouseExited(MouseEvent event);
// Called when the mouse exits a component
}
public interface MouseMotionListener
{
void mouseMoved(MouseEvent event);
// Called when the mouse moves but you are not pressing it
void mouseDragged(MouseEvent event);
// Called when the mouse moves and you are pressing its button
}
15-04-2010
Handling mouse events
Add a mouse listener to a component by calling the addMouseListener method:
Continued…
public class MyMouseListener
implements MouseListener, MouseMotionListener
{
// Implements five + two methods
}
MouseListener listener = new MyMouseListener();
component.addMouseListener(listener);
component.addMouseMotionListener(listener);
Page 70
70
15-04-2010
Mouse Events
Sample program: enhance RectangleComponentViewer program of
Chapter 5; when user clicks on rectangle
component, move the rectangle
15-04-2010
File RectangleComponent.java
01: import java.awt.Graphics;
02: import java.awt.Graphics2D;
03: import java.awt.Rectangle;
04: import javax.swing.JComponent;
05:
06: /**
07: This component lets the user move a rectangle by
08: clicking the mouse.
09: */
10: public class RectangleComponent extends JComponent
11: {
12: public RectangleComponent()
13: {
14: // The rectangle that the paint method draws
15: box = new Rectangle(BOX_X, BOX_Y,
16: BOX_WIDTH, BOX_HEIGHT);
17: }
18: Continued…
Page 71
71
15-04-2010
File RectangleComponent.java
19: public void paintComponent(Graphics g)
20: {
21: super.paintComponent(g);
22: Graphics2D g2 = (Graphics2D) g;
23:
24: g2.draw(box);
25: }
26:
27: /**
28: Moves the rectangle to the given location.
29: @param x the x-position of the new location
30: @param y the y-position of the new location
31: */
32: public void moveTo(int x, int y)
33: {
34: box.setLocation(x, y);
35: repaint();
36: } Continued…
15-04-2010
File RectangleComponent.java
37:
38: private Rectangle box;
39:
40: private static final int BOX_X = 100;
41: private static final int BOX_Y = 100;
42: private static final int BOX_WIDTH = 20;
43: private static final int BOX_HEIGHT = 30;
44: }
Page 72
72
15-04-2010
Mouse Events
Call repaint when you modify the shapes
that paintComponent draws
box.setLocation(x, y);
repaint();
Mouse listener: if the mouse is pressed,
listener moves the rectangle to the mouse
location
Continued…
15-04-2010
Mouse Events
class MousePressListener implements MouseListener
{
public void mousePressed(MouseEvent event)
{
int x = event.getX();
int y = event.getY();
component.moveTo(x, y);
}
// Do-nothing methods
public void mouseReleased(MouseEvent event) {}
public void mouseClicked(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
}
• All five methods of the interface must be implemented;
unused methods can be empty
Page 73
73
15-04-2010
RectangleComponentViewer
Program Output
Figure 4:
Clicking the Mouse Moves the
Rectangle
15-04-2010
File RectangleComponentViewer2.java
01: import java.awt.event.MouseListener;
02: import java.awt.event.MouseEvent;
03: import javax.swing.JFrame;
04:
05: /**
06: This program displays a RectangleComponent.
07: */
08: public class RectangleComponentViewer
09: {
10: public static void main(String[] args)
11: {
12: final RectangleComponent component
= new RectangleComponent();
13:
14: // Add mouse press listener
15:
16: class MousePressListener implements MouseListener
17: { Continued…
Page 74
74
15-04-2010
File RectangleComponentViewer2.java
18: public void mousePressed(MouseEvent event)
19: {
20: int x = event.getX();
21: int y = event.getY();
22: component.moveTo(x, y);
23: }
24:
25: // Do-nothing methods
26: public void mouseReleased(MouseEvent event) {}
27: public void mouseClicked(MouseEvent event) {}
28: public void mouseEntered(MouseEvent event) {}
29: public void mouseExited(MouseEvent event) {}
30: }
31:
32: MouseListener listener = new MousePressListener();
33: component.addMouseListener(listener);
34: Continued…
15-04-2010
File RectangleComponentViewer2.java
35: JFrame frame = new JFrame();
36: frame.add(component);
37:
38: frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
39: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
40: frame.setVisible(true);
41: }
42:
43: private static final int FRAME_WIDTH = 300;
44: private static final int FRAME_HEIGHT = 400;
45: }