Download Chapter 12

Document related concepts
no text concepts found
Transcript
1
Chapter 12: Graphical User Interfaces
Chapter 12
Graphical User Interfaces
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
1
2
Chapter 12: Graphical User Interfaces
Figure 1
A Program with
Four Buttons
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
2
3
Chapter 12: Graphical User Interfaces
Use Panels to Organize Buttons
• JPanel buttonPanel
= new JPanel();
• buttonPanel.add(upButton);
buttonPanel.add(downButton);
. . .
• contentPane.add(buttonPanel,
"South");
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
3
4
Chapter 12: Graphical User Interfaces
Figure 2
Containers with
Separate Layout
Managers
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
4
5
Chapter 12: Graphical User Interfaces
Layout Managers
• BorderLayout (center, south, north, east,
west)
• FlowLayout (left-to-right)
• GridLayout (rectangular grid)
• Default: Content pane has border layout
• Default: Panels have flow layout
• Change default: panel.setLayout(new
GridLayout(4,
3));
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
5
6
Chapter 12: Graphical User Interfaces
Figure 3
The Border Layout Grows
Components
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
6
7
Chapter 12: Graphical User Interfaces
FlowLayout doesn't grow content
• The border layout and grid layout grow
buttons etc. to fit the entire area of the border
or grid
• Remedy: put button(s) inside panel with flow
layout
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
7
8
Chapter 12: Graphical User Interfaces
Figure 4
Grid Layout
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
8
9
Chapter 12: Graphical User Interfaces
Grid Layout
• Add buttons left-to-right/top-to-bottom
panel.add(button7);
panel.add(button8);
panel.add(button9);
panel.add(button4);
. . .
panel.add(buttonCE);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
9
10
Chapter 12: Graphical User Interfaces
Figure 5
Buttons with Labels and
Icons
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
10
11
Chapter 12: Graphical User Interfaces
Buttons
• Specify label and optional icon in constructor
JButton leftButton
= new JButton("left");
leftButton = new JButton("left",
new ImageIcon("left.gif"));
• Add action listener to handle “button click”
event
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
11
12
Chapter 12: Graphical User Interfaces
Program ButtonTest.java
import
import
import
import
import
import
import
import
import
import
import
java.awt.Container;
java.awt.Graphics;
java.awt.Graphics2D;
java.awt.Rectangle;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
java.awt.event.WindowAdapter;
java.awt.event.WindowEvent;
javax.swing.JButton;
javax.swing.JFrame;
javax.swing.JPanel;
public class ButtonTest
{ public static void main(String[] args)
{ ButtonFrame frame = new ButtonFrame();
frame.setTitle("ButtonTest");
frame.show();
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
12
13
Chapter 12: Graphical User Interfaces
}
}
class ButtonFrame extends JFrame
{ public ButtonFrame()
{ final int DEFAULT_FRAME_WIDTH = 300;
final int DEFAULT_FRAME_HEIGHT = 300;
setSize(DEFAULT_FRAME_WIDTH,DEFAULT_FRAME_HEIGHT);
addWindowListener(new WindowCloser());
// construct components
panel = new RectanglePanel();
JPanel buttonPanel = new JPanel();
ActionListener listener = new DirectionListener();
upButton = new JButton("Up");
upButton.addActionListener(listener);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
13
14
Chapter 12: Graphical User Interfaces
downButton = new JButton("Down");
downButton.addActionListener(listener);
leftButton = new JButton("Left");
leftButton.addActionListener(listener);
rightButton = new JButton("Right");
rightButton.addActionListener(listener);
// add components to content pane
Container contentPane = getContentPane();
contentPane.add(panel, "Center");
buttonPanel.add(upButton);
buttonPanel.add(downButton);
buttonPanel.add(leftButton);
buttonPanel.add(rightButton);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
14
15
Chapter 12: Graphical User Interfaces
contentPane.add(buttonPanel, "South");
}
private
private
private
private
private
RectanglePanel panel;
JButton upButton;
JButton downButton;
JButton leftButton;
JButton rightButton;
// inner class definition
private class DirectionListener implements ActionListener
{ public void actionPerformed(ActionEvent event)
{ // find the button that was clicked
Object source = event.getSource();
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
15
16
Chapter 12: Graphical User Interfaces
if (source == upButton)
panel.moveRectangle(0, -1);
else if (source == downButton)
panel.moveRectangle(0, 1);
else if (source == leftButton)
panel.moveRectangle(-1, 0);
else if (source == rightButton)
panel.moveRectangle(1, 0);
}
}
private class WindowCloser extends WindowAdapter
{ public void windowClosing(WindowEvent event)
{ System.exit(0);
}
}
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
16
17
Chapter 12: Graphical User Interfaces
class RectanglePanel extends JPanel
{ public RectanglePanel()
{ rect = new Rectangle(0, 0, RECT_WIDTH, RECT_HEIGHT);
}
public void paintComponent(Graphics g)
{ super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.draw(rect);
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
17
18
Chapter 12: Graphical User Interfaces
/**
Moves the rectangle and repaints it. The rectangle
is moved by multiples of its full width or height.
@param dx the number of width units
@param dy the number of height units
*/
public void moveRectangle(int dx, int dy)
{ rect.translate(dx * RECT_WIDTH, dy * RECT_HEIGHT);
repaint();
}
private Rectangle rect;
private static final int RECT_WIDTH = 20;
private static final int RECT_HEIGHT = 30;
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
18
19
Chapter 12: Graphical User Interfaces
Figure 6
A Frame with a Text Area
and a Text Field
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
19
20
Chapter 12: Graphical User Interfaces
Text Components
• Specify number of rows/characters in
constructor:
tf = new TextField(5);
ta = new TextArea(10, 40);
• Turn edit mode off if you want to display text
ta.setEditable(false);
• Set text programmatically
tf.setText("Hello");
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
20
21
Chapter 12: Graphical User Interfaces
Labels
• Use a label to tag a text field
JLabel label =
new JLabel("Name",
SwingConstants.RIGHT);
• Add label to panel:
panel.add(label);
panel.add(nameField);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
21
22
Chapter 12: Graphical User Interfaces
Program TextTest.java
import
import
import
import
import
import
import
import
import
import
import
import
import
java.awt.Container;
java.awt.GridLayout;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
java.awt.event.WindowAdapter;
java.awt.event.WindowEvent;
java.util.StringTokenizer;
javax.swing.JButton;
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JPanel;
javax.swing.JTextArea;
javax.swing.JTextField;
public class TextTest
{ public static void main(String[] args)
{ TextFrame frame = new TextFrame();
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
22
23
Chapter 12: Graphical User Interfaces
frame.setTitle("TextTest");
frame.show();
}
}
class TextFrame extends JFrame
{ public TextFrame()
{ final int DEFAULT_FRAME_WIDTH = 300;
final int DEFAULT_FRAME_HEIGHT = 300;
setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT);
addWindowListener(new WindowCloser());
// construct components
inputArea = new JTextArea();
resultField = new JTextField(20);
resultField.setEditable(false);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
23
24
Chapter 12: Graphical User Interfaces
calcButton = new JButton("Calculate");
calcButton.addActionListener(new ButtonListener());
// add components to content pane
Container contentPane = getContentPane();
contentPane.add(inputArea, "Center");
// arrange the label and text field in a panel
JPanel resultPanel = new JPanel();
resultPanel.add(new JLabel("Average:"));
resultPanel.add(resultField);
// place the button in a panel
JPanel buttonPanel = new JPanel();
buttonPanel.add(calcButton);
// stack up these two panels in another panel
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
24
25
Chapter 12: Graphical User Interfaces
JPanel southPanel = new JPanel();
southPanel.setLayout(new GridLayout(2, 1));
southPanel.add(resultPanel);
southPanel.add(buttonPanel);
contentPane.add(southPanel, "South");
}
/**
Reads numbers from a string that contains a sequence
of floating-point numbers separated by white space.
@param input the string containing the numbers
@return the numbers that were found in the string
*/
public static double[] getData(String input)
{ StringTokenizer tokenizer = new StringTokenizer(input);
double[] data = new double[tokenizer.countTokens()];
for (int i = 0; i < data.length; i++)
data[i] = Double.parseDouble(tokenizer.nextToken());
return data;
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
25
26
Chapter 12: Graphical User Interfaces
}
/**
Computes the average of an array of floating-point numbers.
@param data the numbers to average
@return the average, or 0 if the array was empty
*/
public static double average(double[] data)
{ if (data.length == 0) return 0;
double sum = 0;
for (int i = 0; i < data.length; i++)
sum = sum + data[i];
return sum / data.length;
}
private JTextArea inputArea;
private JTextField resultField;
private JButton calcButton;
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
26
27
Chapter 12: Graphical User Interfaces
private class ButtonListener implements ActionListener
{ public void actionPerformed(ActionEvent event)
{ // get user input from text area
double[] data = getData(inputArea.getText());
// compute average and display in result field
double avg = average(data);
resultField.setText("” + avg);
}
}
private class WindowCloser extends WindowAdapter
{ public void windowClosing(WindowEvent event)
{ System.exit(0);
}
}
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
27
28
Chapter 12: Graphical User Interfaces
Figure 7
A Combo Box, Radio
Buttons, and Check
Boxes
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
28
29
Chapter 12: Graphical User Interfaces
Radio Buttons
• Radio buttons are mutually exclusive
• Button group turns one button off when the
next one is turned on
sButton = new JRadioButton("Small");
mButton = new JRadioButton("Medium");
lButton = new JRadioButton("Large");
buttonGroup.add(sbutton);
buttonGroup.add(mbutton);
buttonGroup.add(lbutton)
• Still need to add
to
panel
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
29
30
Chapter 12: Graphical User Interfaces
Check Boxes
• Similar to radio button, not mutually
exclusive
JCheckBox it = new JCheckBox("Italic");
• Test if selected
if (it.isSelected()) . . .
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
30
31
Chapter 12: Graphical User Interfaces
Borders
• Use border to group related components
• Add border to panel holding components
• panel.setBorder(new
TitledBorder(new
EtchedBorder(), "Title"));
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
31
32
Chapter 12: Graphical User Interfaces
Figure 8
An Opened Combo Box
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
32
33
Chapter 12: Graphical User Interfaces
Combo boxes
• Use less space than radio buttons
• Users can type other values
• “Combo” between list selection and text field
• JComboBox faceName = new JComboBox();
faceName.addItem("Serif");
faceName.addItem("SansSerif");
. . .
• Get user selection
sel= (String)faceName.getSelectedItem();
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
33
34
Chapter 12: Graphical User Interfaces
Program ChoiceTest.java
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
java.awt.Container;
java.awt.Font;
java.awt.GridLayout;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
java.awt.event.WindowAdapter;
java.awt.event.WindowEvent;
javax.swing.ButtonGroup;
javax.swing.JButton;
javax.swing.JCheckBox;
javax.swing.JComboBox;
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JPanel;
javax.swing.JRadioButton;
javax.swing.JTextField;
javax.swing.border.EtchedBorder;
javax.swing.border.TitledBorder;
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
34
35
Chapter 12: Graphical User Interfaces
public class ChoiceTest
{ public static void main(String[] args)
{ ChoiceFrame frame = new ChoiceFrame();
frame.setTitle("ChoiceTest");
frame.show();
}
}
class ChoiceFrame extends JFrame
{ public ChoiceFrame()
{ final int DEFAULT_FRAME_WIDTH = 300;
final int DEFAULT_FRAME_HEIGHT = 300;
setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT);
addWindowListener(new WindowCloser());
// construct components
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
35
36
Chapter 12: Graphical User Interfaces
sampleField = new JTextField
("Computing Concepts with Java Essentials");
sampleField.setEditable(false);
ChoiceListener listener = new ChoiceListener();
facenameCombo = new JComboBox();
facenameCombo.addItem("Serif");
facenameCombo.addItem("SansSerif");
facenameCombo.addItem("Monospaced");
facenameCombo.setEditable(true);
facenameCombo.addActionListener(listener);
italicCheckBox = new JCheckBox("Italic");
italicCheckBox.addActionListener(listener);
boldCheckBox = new JCheckBox("Bold");
boldCheckBox.addActionListener(listener);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
36
37
Chapter 12: Graphical User Interfaces
smallButton = new JRadioButton("Small");
smallButton.setSelected(true);
smallButton.addActionListener(listener);
mediumButton = new JRadioButton("Medium");
mediumButton.addActionListener(listener);
largeButton = new JRadioButton("Large");
largeButton.addActionListener(listener);
// add radio buttons to button group
ButtonGroup sizeGroup = new ButtonGroup();
sizeGroup.add(smallButton);
sizeGroup.add(mediumButton);
sizeGroup.add(largeButton);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
37
38
Chapter 12: Graphical User Interfaces
// add components to panels
JPanel facenamePanel = new JPanel();
facenamePanel.add(facenameCombo);
JPanel sizeGroupPanel = new JPanel();
sizeGroupPanel.add(smallButton);
sizeGroupPanel.add(mediumButton);
sizeGroupPanel.add(largeButton);
sizeGroupPanel.setBorder
(new TitledBorder(new EtchedBorder(), "Size"));
JPanel styleGroupPanel = new JPanel();
styleGroupPanel.add(italicCheckBox);
styleGroupPanel.add(boldCheckBox);
styleGroupPanel.setBorder
(new TitledBorder(new EtchedBorder(), "Style"));
// line up component panels
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
38
39
Chapter 12: Graphical User Interfaces
JPanel southPanel = new JPanel();
southPanel.setLayout(new GridLayout(3, 1));
southPanel.add(facenamePanel);
southPanel.add(sizeGroupPanel);
southPanel.add(styleGroupPanel);
// add panels to content pane
Container contentPane = getContentPane();
contentPane.add(sampleField, "Center");
contentPane.add(southPanel, "South");
setSampleFont();
}
/**
Gets user choice for font name, style, and size
and sets the font of the text field.
*/
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
39
40
Chapter 12: Graphical User Interfaces
public void setSampleFont()
{ // get font name
String facename
= (String)facenameCombo.getSelectedItem();
// get font style
int style = 0;
if (italicCheckBox.isSelected())
style = style + Font.ITALIC;
if (boldCheckBox.isSelected())
style = style + Font.BOLD;
// get font size
final int SMALL_SIZE = 12;
final int MEDIUM_SIZE = 16;
final int LARGE_SIZE = 24;
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
40
41
Chapter 12: Graphical User Interfaces
int size = 0;
if (smallButton.isSelected())
size = SMALL_SIZE;
else if (mediumButton.isSelected())
size = MEDIUM_SIZE;
else if (largeButton.isSelected())
size = LARGE_SIZE;
// set font of text field
sampleField.setFont(new Font(facename, style, size));
sampleField.repaint();
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
41
42
Chapter 12: Graphical User Interfaces
private
private
private
private
private
private
private
JTextField sampleField;
JCheckBox italicCheckBox;
JCheckBox boldCheckBox;
JRadioButton smallButton;
JRadioButton mediumButton;
JRadioButton largeButton;
JComboBox facenameCombo;
private class ChoiceListener implements ActionListener
{ public void actionPerformed(ActionEvent event)
{ setSampleFont();
}
}
private class WindowCloser extends WindowAdapter
{ public void windowClosing(WindowEvent event)
{ System.exit(0);
}
}
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
42
43
Chapter 12: Graphical User Interfaces
Figure 9
Pulldown Menus
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
43
44
Chapter 12: Graphical User Interfaces
Menus
• Add menu bar to frame
JMenuBar bar = new JMenuBar();
frame.setJMenuBar(bar);
• Add menus to the menu bar
JMenu fileMenu
= new JMenu("File");
bar.add(fileMenu);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
44
45
Chapter 12: Graphical User Interfaces
Menu items
• Add menu items to the menu
JMenuItem fileNew
= new JMenuItem("New");
• Add action listener to the menu item
ActionListener l = ...;
fileNew.addActionListener(l);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
45
46
Chapter 12: Graphical User Interfaces
Program MenuTest.java
import
import
import
import
import
import
import
import
import
import
import
import
import
import
java.awt.Container;
java.awt.Graphics;
java.awt.Graphics2D;
java.awt.Rectangle;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
java.awt.event.WindowAdapter;
java.awt.event.WindowEvent;
java.util.Random;
javax.swing.JFrame;
javax.swing.JMenu;
javax.swing.JMenuBar;
javax.swing.JMenuItem;
javax.swing.JPanel;
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
46
47
Chapter 12: Graphical User Interfaces
public class MenuTest
{ public static void main(String[] args)
{ MenuFrame frame = new MenuFrame();
frame.setTitle("MenuTest");
frame.show();
}
}
class MenuFrame extends JFrame
{ public MenuFrame()
{ final int DEFAULT_FRAME_WIDTH = 300;
final int DEFAULT_FRAME_HEIGHT = 300;
setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT);
addWindowListener(new WindowCloser());
// add drawing panel to content pane
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
47
48
Chapter 12: Graphical User Interfaces
panel = new RectanglePanel();
Container contentPane = getContentPane();
contentPane.add(panel, "Center");
// construct menu
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
MenuListener listener = new MenuListener();
newMenuItem = new JMenuItem("New");
fileMenu.add(newMenuItem);
newMenuItem.addActionListener(listener);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
48
49
Chapter 12: Graphical User Interfaces
exitMenuItem = new JMenuItem("Exit");
fileMenu.add(exitMenuItem);
exitMenuItem.addActionListener(listener);
JMenu editMenu = new JMenu("Edit");
menuBar.add(editMenu);
JMenuItem moveMenu = new JMenu("Move");
editMenu.add(moveMenu);
upMenuItem = new JMenuItem("Up");
moveMenu.add(upMenuItem);
upMenuItem.addActionListener(listener);
downMenuItem = new JMenuItem("Down");
moveMenu.add(downMenuItem);
downMenuItem.addActionListener(listener);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
49
50
Chapter 12: Graphical User Interfaces
leftMenuItem = new JMenuItem("Left");
moveMenu.add(leftMenuItem);
leftMenuItem.addActionListener(listener);
rightMenuItem = new JMenuItem("Right");
moveMenu.add(rightMenuItem);
rightMenuItem.addActionListener(listener);
randomizeMenuItem = new JMenuItem("Randomize");
editMenu.add(randomizeMenuItem);
randomizeMenuItem.addActionListener(listener);
}
private
private
private
private
private
private
JMenuItem
JMenuItem
JMenuItem
JMenuItem
JMenuItem
JMenuItem
exitMenuItem;
newMenuItem;
upMenuItem;
downMenuItem;
leftMenuItem;
rightMenuItem;
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
50
51
Chapter 12: Graphical User Interfaces
private JMenuItem randomizeMenuItem;
private RectanglePanel panel;
private class MenuListener implements ActionListener
{ public void actionPerformed(ActionEvent event)
{ // find the menu that was selected
Object source = event.getSource();
if (source == exitMenuItem)
System.exit(0);
else if (source == newMenuItem)
panel.reset();
else if (source == upMenuItem)
panel.moveRectangle(0, -1);
else if (source == downMenuItem)
panel.moveRectangle(0, 1);
else if (source == leftMenuItem)
panel.moveRectangle(-1, 0);
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
51
52
Chapter 12: Graphical User Interfaces
else if (source == rightMenuItem)
panel.moveRectangle(1, 0);
else if (source == randomizeMenuItem)
panel.randomize();
}
}
private class WindowCloser extends WindowAdapter
{ public void windowClosing(WindowEvent event)
{ System.exit(0);
}
}
}
class RectanglePanel extends JPanel
{ public RectanglePanel()
{ rect = new Rectangle(0, 0, RECT_WIDTH, RECT_HEIGHT);
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
52
53
Chapter 12: Graphical User Interfaces
public void paintComponent(Graphics g)
{ super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.draw(rect);
}
/**
Resets the rectangle to the top left corner.
*/
public void reset()
{ rect.setLocation(0, 0);
repaint();
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
53
54
Chapter 12: Graphical User Interfaces
/**
Moves the rectangle to a random position.
*/
public void randomize()
{ Random generator = new Random();
rect.setLocation(generator.nextInt(getWidth()),
generator.nextInt(getHeight()));
repaint();
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
54
55
Chapter 12: Graphical User Interfaces
/**
Moves the rectangle and repaints it. The rectangle
is moved by multiples of its full width or height.
@param dx the number of width units
@param dy the number of height units
*/
public void moveRectangle(int dx, int dy)
{ rect.translate(dx * RECT_WIDTH, dy * RECT_HEIGHT);
repaint();
}
private Rectangle rect;
private static int RECT_WIDTH = 20;
private static int RECT_HEIGHT = 30;
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
55
56
Chapter 12: Graphical User Interfaces
Figure 10
A Color Mixer
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
56
57
Chapter 12: Graphical User Interfaces
Figure 11
A Demonstration Application from
the Java Development Kit
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
57
58
Chapter 12: Graphical User Interfaces
Exploring the Documentation
• Don't try to understand all methods
• Focus on what you need to do your job
– How do I construct a slider?
– How can I get notified when the user has moved
it?
– How can I tell what the user has set it to?
• When you complete the basics, look again
– How about those “tick marks”?
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
58
59
Chapter 12: Graphical User Interfaces
Figure 12
A Mysterious Entry in the JSlider
Documentation
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
59
60
Chapter 12: Graphical User Interfaces
How to construct a slider
• JSlider()
Has range (0,100)
• JSlider(int min, int max, int
value)
Can specify range and initial value
• JSlider(BoundedRangeModel m)
appears to be some internal mechanism
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
60
61
Chapter 12: Graphical User Interfaces
How to get notifications
• Look for “addXxxListener”:
void addChangeListener(ChangeListener l)
• What is a change listener? It has a single
method
void stateChanged(ChangeEvent e)
• Plan: Add a change listener, read slider state
and update color in that method
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
61
62
Chapter 12: Graphical User Interfaces
How to get slider setting
• Look at all methods that start with “get”:
int getValue()
Returns the slider's value
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
62
63
Chapter 12: Graphical User Interfaces
Program SliderTest.java
import
import
import
import
import
import
import
import
import
import
import
import
java.awt.Color;
java.awt.Container;
java.awt.GridLayout;
java.awt.event.WindowAdapter;
java.awt.event.WindowEvent;
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JPanel;
javax.swing.JSlider;
javax.swing.SwingConstants;
javax.swing.event.ChangeListener;
javax.swing.event.ChangeEvent;
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
63
64
Chapter 12: Graphical User Interfaces
public class SliderTest
{ public static void main(String[] args)
{ SliderFrame frame = new SliderFrame();
frame.setTitle("SliderTest");
frame.show();
}
}
class SliderFrame extends JFrame
{ public SliderFrame()
{ final int DEFAULT_FRAME_WIDTH = 300;
final int DEFAULT_FRAME_HEIGHT = 300;
setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT);
addWindowListener(new WindowCloser());
// construct components
colorPanel = new JPanel();
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
64
65
Chapter 12: Graphical User Interfaces
ColorListener listener = new ColorListener();
redSlider = new JSlider(0, 100, 100);
redSlider.addChangeListener(listener);
greenSlider = new JSlider(0, 100, 70);
greenSlider.addChangeListener(listener);
blueSlider = new JSlider(0, 100, 70);
blueSlider.addChangeListener(listener);
// fill content pane
JPanel southPanel = new JPanel();
southPanel.setLayout(new GridLayout(3, 2));
southPanel.add(new JLabel("Red",
SwingConstants.RIGHT));
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
65
66
Chapter 12: Graphical User Interfaces
southPanel.add(redSlider);
southPanel.add(new JLabel("Green",
SwingConstants.RIGHT));
southPanel.add(greenSlider);
southPanel.add(new JLabel("Blue",
SwingConstants.RIGHT));
southPanel.add(blueSlider);
Container contentPane = getContentPane();
contentPane.add(colorPanel, "Center");
contentPane.add(southPanel, "South");
setSampleColor();
}
/**
Reads the slider values and sets the panel to
the selected color.
*/
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
66
67
Chapter 12: Graphical User Interfaces
public void setSampleColor()
{ // read slider values
float red = 0.01F * redSlider.getValue();
float green = 0.01F * greenSlider.getValue();
float blue = 0.01F * blueSlider.getValue();
// set panel background to selected color
colorPanel.setBackground(new Color(red, green, blue));
colorPanel.repaint();
}
private
private
private
private
JPanel colorPanel;
JSlider redSlider;
JSlider greenSlider;
JSlider blueSlider;
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
67
68
Chapter 12: Graphical User Interfaces
private class ColorListener implements ChangeListener
{ public void stateChanged(ChangeEvent event)
{ setSampleColor();
}
}
private class WindowCloser extends WindowAdapter
{ public void windowClosing(WindowEvent event)
{ System.exit(0);
}
}
}
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
68
69
Chapter 12: Graphical User Interfaces
Figure 13
Visual Programming Environment
©2000, John Wiley & Sons, Inc.
Horstmann/Java Essentials, 2/e
69
Related documents