import java.awt.

Download Report

Transcript import java.awt.

Chapter 14
More Swing Objects





Chapter 14
Menus
Making GUIs Pretty (and More Functional)
Box Containers and Box Layout Managers
More on Events and Listeners
Another Look at the Swing Class Hierarchy
Java: an Introduction to Computer Science & Programming - Walter Savitch
1
Menus

Three Swing classes used to put a menu in a
program:
AbstractButton
» JMenuBar
» JMenu
JMenuItem
» JMenuItem
JButton
JMenu

Chapter 14
Menu items behave in the same way as buttons
Java: an Introduction to Computer Science & Programming - Walter Savitch
2
A GUI with
a Menu
JMenu memoMenu = new JMenu("Memos");
JMenuItem m;
Create a menu
m = new JMenuItem("Save Memo 1");
m.addActionListener(this);
memoMenu.add(m);
Create a menu item
m = new JMenuItem("Save Memo 2");
m.addActionListener(this);
A menu item uses an
memoMenu.add(m);
action listener the same
. . .
JMenuBar mBar = new JMenuBar(); way a button does.
mBar.add(memoMenu);
setJMenuBar(mBar);
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
3
A GUI with
a Menu
JMenu memoMenu = new JMenu("Memos");
JMenuItem m;
m = new JMenuItem("Save Memo 1");
Each menu item is added
m.addActionListener(this);
to the menu.
memoMenu.add(m);
m = new JMenuItem("Save Memo 2");
m.addActionListener(this);
The menu is added to the
memoMenu.add(m);
menu bar.
. . .
JMenuBar mBar = new JMenuBar();
mBar.add(memoMenu);
setJMenuBar(mBar);
One way to add a menu
bar to a JFrame
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
4
Display 14.1
GUI with a Menu (1/4)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MemoGUI extends JFrame implements ActionListener
{
public static final int WIDTH = 600;
public static final int HEIGHT = 300;
public static final int LINES = 10;
public static final int CHAR_PER_LINE = 40;
private JTextArea theText;
private String memo1 = "No Memo 1.";
private String memo2 = "No Memo 2.";
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
5
public MemoGUI()
Display 14.1
{
GUI with a Menu (2/4)
setSize(WIDTH, HEIGHT);
addWindowListener(new WindowDestroyer());
setTitle("Memo Saver");
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
JMenu memoMenu = new JMenu("Memos");
JMenuItem m;
m = new JMenuItem("Save Memo 1");
m.addActionListener(this);
memoMenu.add(m);
m = new JMenuItem("Save Memo 2");
m.addActionListener(this);
memoMenu.add(m);
m = new JMenuItem("Get Memo 1");
m.addActionListener(this);
memoMenu.add(m);
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
6
m = new JMenuItem("Get Memo 2");
m.addActionListener(this);
memoMenu.add(m);
Display 14.1
GUI with a Menu (3/4)
m = new JMenuItem("Clear");
m.addActionListener(this);
memoMenu.add(m);
m = new JMenuItem("Exit");
m.addActionListener(this);
memoMenu.add(m);
JMenuBar mBar = new JMenuBar();
mBar.add(memoMenu);
setJMenuBar(mBar);
JPanel textPanel = new JPanel();
textPanel.setBackground(Color.blue);
theText = new JTextArea(LINES, CHAR_PER_LINE);
theText.setBackground(Color.white);
textPanel.add(theText);
contentPane.add(textPanel, BorderLayout.CENTER);
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
7
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if (actionCommand.equals("Save Memo 1"))
memo1 = theText.getText();
else if (actionCommand.equals("Save Memo 2"))
memo2 = theText.getText();
else if (actionCommand.equals("Clear"))
theText.setText("");
else if (actionCommand.equals("Get Memo 1"))
theText.setText(memo1);
else if (actionCommand.equals("Get Memo 2"))
theText.setText(memo2);
else if (actionCommand.equals("Exit"))
System.exit(0);
else
theText.setText("Error in memo interface");
}
public static void main(String[] args)
{
MemoGUI gui = new MemoGUI();
Display 14.1
gui.setVisible(true);
GUI with a Menu (4/4)
}
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
8
Nested Menus





JMenu is a descendant of JMenuItem
Every JMenu object is also a JMenuItem
A JMenu can be a menu item in another menu
This allows nested menus
Clicking on a nested menu shows the items in the
nested menu and allows them to be selected.
AbstractButton
JMenuItem
JButton
JMenu
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
9
Making GUIs Pretty
(and More Functional)




Chapter 14
Adding Icons
The JScrollPane Class for Scroll Bars
Adding Borders
Changing the Look and Feel
Java: an Introduction to Computer Science & Programming - Walter Savitch
10
Using Icons



Icons are (small) pictures
Icons may be added to labels, buttons, and menu items.
The ImageIcon class can be used to convert a picture to an icon:
ImageIcon SmileyFaceIcon = new ImageIcon(“smiley.gif”);

The setIcon method can be used to add an icon to a component:
JLabel helloLabel = new JLabel(“Hello”);
ImageIcon dukeWavingIcon =
new ImageIcon(“duke_waving.gif”);
helloLabel.setIcon(dukeWavingIcon);
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
11
Display 14.2
Using Icons (1/4)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class IconDemo extends JFrame implements ActionListener
{
public static final int WIDTH = 400;
public static final int HEIGHT = 200;
private JTextField message;
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
12
Display 14.2
Using Icons (2/4)
public IconDemo()
{
setSize(WIDTH, HEIGHT);
addWindowListener(new WindowDestroyer());
setTitle("Icon Demonstration");
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new BorderLayout());
JLabel niceLabel = new JLabel("Nice day!");
ImageIcon smileyIcon = new ImageIcon("smiley.gif");
niceLabel.setIcon(smileyIcon);
content.add(niceLabel, BorderLayout.NORTH);
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
13
Display 14.2
Using Icons (3/4)
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
JButton helloButton = new JButton("Hello");
ImageIcon dukeWavingIcon = new ImageIcon("duke_waving.gif");
helloButton.setIcon(dukeWavingIcon);
helloButton.addActionListener(this);
buttonPanel.add(helloButton);
JButton byeButton = new JButton("Good bye");
ImageIcon dukeStandingIcon =
new ImageIcon("duke_standing.gif");
byeButton.setIcon(dukeStandingIcon);
byeButton.addActionListener(this);
buttonPanel.add(byeButton);
content.add(buttonPanel, BorderLayout.SOUTH);
message = new JTextField(30);
content.add(message, BorderLayout.CENTER);
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
14
Display 14.2
Using Icons (4/4)
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Hello"))
message.setText("Glad to meet you!");
else if (e.getActionCommand().equals("Good bye"))
message.setText(
"OK, click the upper right button. I'll miss you.");
else
System.out.println("Error in button interface.");
}
public static void main(String[] args)
{
IconDemo iconGui = new IconDemo();
iconGui.setVisible(true);
}
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
15
Some Methods in the Classes
Jbutton and Jlabel (1/3)
public JButton(), public JLabel()
- Creates a button or label with no text or icon on it.
- You will later use setText and setIcon with the button or menu item.
 public JButton(String text)
 public JLabel(String text)
- Creates a button or label with the text on it.
 public JButton(ImageIcon picture)
 public JLabel(ImageIcon picture)
- Creates a button or label with the icon picture on it.
 public JButton(String text, ImageIcon picture)
 public JLabel(String text, ImageIcon picture,
int horizontalAlignment)
- Creates a button or label with both the text and the icon picture on it.
- horizontalAlignment is one of the constants SwingConstants.LEFT,
SwingConstants.CENTER, SwingConstants.RIGHT,
SwingConstants.LEADING, or SwingConstants.TRAILING.

Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
16
Some Methods in the Classes
Jbutton and Jlabel (2/3)




public void setText(String text)
- Makes text the only text on the button or label.
public void setIcon(ImageIcon picture)
- Makes picture the only icon on the button or label.
public void setMargin(Insets margin)
- JButton has the method setMargin, but JLabel does not.
- The method setMargin sets the size of the margin around the text and icon
in the button.
- public void setMargin(new Insets(int top, int left,
int bottom, int right))
public void setPreferredSize(
Dimension preferredSize)
- Sets the preferred size. The layout manager is not required to use the
preferred size.
- public void setPreferredSize(new Dimension(int width,
int height))
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
17
Some Methods in the Classes
Jbutton and Jlabel (3/3)
public void setMaximumSize(Dimension maximumSize)
- Sets the maximum size.
- public void setMaximumSize(new Dimension(int width,
int height))
 public void setMinimumSize(Dimension minimumSize)
- Sets the minimum size.
- public void setMinimumSize(new Dimension(int width,
int height))
 public void setVerticalTextPosition(int textPosition)
- Sets the vertical position of the text relative to the icon.
- The textPosition should be one of the constants SwingConstants.TOP,
SwingConstants.CENTER or SwingConstants.BOTTOM.
 public void setHorizontalTextPosition(int textPosition)
- Sets the horizontal position of the text relative to the icon.
- The textPosition should be one of the constants
SwingConstants.RIGHT, SwingConstants.LEFT,
SwingConstants.CENTER, or SwingConstants.LEADING,
SwingConstants.TRAILING.

Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
18
The JScrollPane Class for Scroll Bars




A view port is used when not all information can be displayed on
screen at once.
Scroll bars move a view port around to show different parts of the
information.
JScrollPane is a class that can provide a view port with scroll bars.
An example using JScrollPane with a JTextArea called theText
and a JPanel called textPanel:
JScrollPane scrolledText = new JScrollPane(theText);
textPanel.add(scrolledText);
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
19
View Port for A Text Area
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
20
Some Methods and Constants
in the Class JScrollPane
public JScrollPane(Component objectToBeScrolled)
- Creates a new JScrollPane for the objectToBeScrolled.
 public void setHorizontalScrollBarPolicy(int policy)

- Sets the policy for showing the horizontal scroll bar.
- The policy should be one of
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED
 public void setVerticalScrollBarPolicy(int policy)
- Sets the policy for showing the vertical scroll bar.
 JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED
 JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
- Constants in the class JScrollPane.
- The phrase “AS_NEEDED” means the scroll bar is only shown when it is
needed.
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
21
Display 14.5
TextArea with
Scroll Bars(1/4)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ScrollBarDemo extends JFrame implements ActionListener
{
public static final int WIDTH = 600;
public static final int HEIGHT = 300;
public static final int LINES = 10;
public static final int CHAR_PER_LINE = 40;
private JTextArea theText;
private String memo1 = "No Memo 1.";
private String memo2 = "No Memo 2.";
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
22
public ScrollBarDemo()
{
setSize(WIDTH, HEIGHT);
addWindowListener(new WindowDestroyer());
setTitle("Scrolling Memo Saver");
Display 14.5
TextArea with
Scroll Bars(2/4)
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
JMenu memoMenu = new JMenu("Memos");
JMenuItem m;
m = new JMenuItem("Save Memo 1");
m.addActionListener(this);
memoMenu.add(m);
m = new JMenuItem("Save Memo 2");
m.addActionListener(this);
memoMenu.add(m);
m = new JMenuItem("Get Memo 1");
m.addActionListener(this);
memoMenu.add(m);
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
23
m = new JMenuItem("Get Memo 2");
Display 14.5
m.addActionListener(this);
memoMenu.add(m);
TextArea with
m = new JMenuItem("Clear");
Scroll Bars(3/4)
m.addActionListener(this);
memoMenu.add(m);
m = new JMenuItem("Exit");
m.addActionListener(this);
memoMenu.add(m);
JMenuBar mBar = new JMenuBar();
mBar.add(memoMenu);
setJMenuBar(mBar);
JPanel textPanel = new JPanel();
textPanel.setBackground(Color.blue);
theText = new JTextArea(LINES, CHAR_PER_LINE);
theText.setBackground(Color.white);
JScrollPane scrolledText = new JScrollPane(theText);
scrolledText.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrolledText.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textPanel.add(scrolledText);
contentPane.add(textPanel, BorderLayout.CENTER);
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
24
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if (actionCommand.equals("Save Memo 1"))
memo1 = theText.getText();
else if (actionCommand.equals("Save Memo 2"))
memo2 = theText.getText();
else if (actionCommand.equals("Clear"))
theText.setText("");
else if (actionCommand.equals("Get Memo 1"))
theText.setText(memo1);
else if (actionCommand.equals("Get Memo 2"))
theText.setText(memo2);
Display 14.5
else if (actionCommand.equals("Exit"))
TextArea with
System.exit(0);
Scroll Bars(4/4)
else
theText.setText("Error in memo interface");
}
public static void main(String[] args)
{
ScrollBarDemo guiMemo = new ScrollBarDemo();
guiMemo.setVisible(true);
}
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
25
Execution Result of
ScrollBarDemo.java
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
26
Adding Borders



A border is an area that frames a component.
Swing provides several different types of borders:
» BevelBorder—makes component look raised or lowered
» EtchedBorder—similar to BevelBorder but can’t set size
» EmptyBorder—extra space around the component
» LineBorder—colored border of a given thickness
» MatteBorder—similar to LineBorder but can adjust
thickness on each side of the component
An example of adding a bevel border to a button:
testButton.setBorder(new BevelBorder(BevelBorder.LOWERED));
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
27
Display 14.7
Different Borders
(1/4)
import
import
import
import
javax.swing.*;
java.awt.*;
java.awt.event.*;
javax.swing.border.*;
public class BorderDemo extends JFrame implements ActionListener
{
public static final int WIDTH = 400;
public static final int HEIGHT = 300;
private JTextField name;
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
28
public BorderDemo()
Display 14.7
{
Different Borders
setTitle("Name Tester with Borders");
(2/4)
setSize(WIDTH, HEIGHT);
addWindowListener(new WindowDestroyer());
Container content = getContentPane();
content.setLayout(new GridLayout(2, 1));
JPanel namePanel = new JPanel();
namePanel.setLayout(new BorderLayout());
namePanel.setBackground(Color.white);
name = new JTextField(20);
//The following border is not as dramatic as others,
//but look closely and you will see it.
name.setBorder(new EtchedBorder(Color.green, Color.blue));
namePanel.add(name, BorderLayout.SOUTH);
JLabel nameLabel = new JLabel("Enter your name here:");
//The following does insert space around the label.
//To see the difference, comment out the following line:
nameLabel.setBorder(new EmptyBorder(20, 10, 0, 0));
namePanel.add(nameLabel, BorderLayout.CENTER);
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
29
namePanel.setBorder(new LineBorder(Color.black, 10));
content.add(namePanel);
Display 14.7
Different Borders
JPanel buttonPanel = new JPanel();
(3/4)
buttonPanel.setLayout(new FlowLayout());
JButton testButton = new JButton("Test");
testButton.addActionListener(this);
testButton.setBorder(
new BevelBorder(BevelBorder.LOWERED));
buttonPanel.add(testButton);
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(this);
clearButton.setBorder(
new BevelBorder(BevelBorder.RAISED));
buttonPanel.add(clearButton);
buttonPanel.setBorder(
new MatteBorder(60, 40, 30, 20, Color.pink));
content.add(buttonPanel);
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
30
Display 14.7
Different Borders
(4/4)
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Test"))
name.setText("A very good name!");
else if (e.getActionCommand().equals("Clear"))
name.setText("");
else
name.setText("Error in window interface.");
}
public static void main(String[] args)
{
BorderDemo w = new BorderDemo();
w.setVisible(true);
}
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
31
Execution Result of
BorderDemo.java
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
32
Changing the Look and Feel



Chapter 14
Look and feel refers to the general appearance of the GUI,
including:
» Shape and exact placement of buttons
» Default colors
Three standard choices for look and feel:
» Metal—considered the standard Java look and feel
» Motif—often considered the standard Unix look and feel
» Windows—looks like the windows you get with the Windows
operating system
A Macintosh look and feel is also available
Java: an Introduction to Computer Science & Programming - Walter Savitch
33
Class Names for
Three Looks and Feels

Metal
- “javax.swing.plaf.metal.MetalLookAndFeel”

Motif
- “com.sun.java.swing.plaf.motif.MotifLookAndFeel”

Windows
- “com.sun.java.swing.plaf.windows.
WindowsLookAndFeel”
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
34
An Example of Changing the Look
and Feel of a GUI
try
Fully qualified class name—
{
includes directory path
UIManager.setLookAndFeel(
“com.sun.java.swing.plaf.motif.MotifLookAndFeel”);
SwingUtilities.updateComponentTreeUI(this);
}
Try and catch necessary
catch (Exception e)
because any one of four
{
exceptions could be thrown
System.out.println(
“Could not load the Motif look and feel”);
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
35
Display 14.11
Looks and Feels
(1/3)
import javax.swing.*;
import java.awt.*;
public class LookNFeelSample extends JFrame
{
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
36
public LookNFeelSample(String lookNFeelClassName, String title)
{
setSize(WIDTH, HEIGHT);
addWindowListener(new WindowDestroyer());
Display 14.11
setTitle(title);
Looks and Feels
Container content = getContentPane();
(2/3)
content.setLayout(new FlowLayout());
JButton aButton = new JButton("A Button");
content.add(aButton);
JLabel aLabel = new JLabel("This is a label.");
content.add(aLabel);
try
{
UIManager.setLookAndFeel(lookNFeelClassName);
SwingUtilities.updateComponentTreeUI(this);
}
catch (Exception e)
{
System.out.println("Look and feel problem.");
}
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
37
Display 14.11
Looks and Feels
(3/3)
public static void main(String[] args)
{
LookNFeelSample metalGUI = new LookNFeelSample(
"javax.swing.plaf.metal.MetalLookAndFeel",
"Metal Look and Feel");
metalGUI.setVisible(true);
LookNFeelSample motifGUI = new LookNFeelSample(
"com.sun.java.swing.plaf.motif.MotifLookAndFeel",
"Motif Look and Feel");
motifGUI.setVisible(true);
LookNFeelSample windowsGUI = new LookNFeelSample(
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel",
"Windows Look and Feel");
windowsGUI.setVisible(true);
}
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
38
Execution Result of
LookNFeelSample.java
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
39
Box Layout Manager




Chapter 14
Useful for a single column or single row of
components
Specify X_AXIS (horizontal) or Y_AXIS (vertical)
layout as second parameter to constructor for layout
manager
Provides a means of separating components in a row
or column
» Strut—allocates a fixed amount of space between
two components
» Glue—allocates a variable amount of space
between two components
A Box container is a container that is automatically
given a BoxLayout manager.
Java: an Introduction to Computer Science & Programming - Walter Savitch
40
Box Layout Versus Other Layouts




Chapter 14
Horizontal box layout is similar to flow layout.
Vertical box layout is similar to grid layout with only
one column.
Big advantage of box layout is control over spacing
using struts and glue.
Note that struts and glue should not be used with
other layout managers.
Java: an Introduction to Computer Science & Programming - Walter Savitch
41
Box Layout Demo Program
Specifies a
horizontal layout
JPanel horizontalPanel = new JPanel();
horizontalPanel.setLayout(
new BoxLayout(horizontalPanel, BoxLayout.X_AXIS));
Component horizontalStrut =
Box.createHorizontalStrut(HORIZONTAL_STRUT_SIZE);
horizontalPanel.add(horizontalStrut);
JButton hStopButton = new JButton("Red");
hStopButton.addActionListener(this);
horizontalPanel.add(hStopButton);
Static method in Box class used to create
a strut of a particular size for spacing
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
42
Display 14.13
BoxLayout
(1/5)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BoxLayoutDemo extends Jframe implements ActionListener
{
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
public static final int HORIZONTAL_STRUT_SIZE = 15;
public static final int VERTICAL_STRUT_SIZE = 10;
private JPanel colorPanel;
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
43
public BoxLayoutDemo()
{
setSize(WIDTH, HEIGHT);
addWindowListener(new WindowDestroyer());
setTitle("Box Demonstration");
Container content = getContentPane();
content.setLayout(new BorderLayout());
Display 14.13
BoxLayout
(2/5)
colorPanel = new JPanel();
colorPanel.setBackground(Color.blue);
content.add(colorPanel, BorderLayout.CENTER);
//Horizontal buttons at bottom of frame:
JPanel horizontalPanel = new JPanel();
horizontalPanel.setLayout(
new BoxLayout(horizontalPanel, BoxLayout.X_AXIS));
Component horizontalStrut =
Box.createHorizontalStrut(HORIZONTAL_STRUT_SIZE);
horizontalPanel.add(horizontalStrut);
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
44
JButton hStopButton = new JButton("Red");
hStopButton.addActionListener(this);
horizontalPanel.add(hStopButton);
Display 14.13
BoxLayout
(3/5)
Component horizontalStrut2 =
Box.createHorizontalStrut(HORIZONTAL_STRUT_SIZE);
horizontalPanel.add(horizontalStrut2);
JButton hGoButton = new JButton("Green");
hGoButton.addActionListener(this);
horizontalPanel.add(hGoButton);
content.add(horizontalPanel, BorderLayout.SOUTH);
//Vertical buttons on right side of frame:
JPanel verticalPanel = new JPanel();
verticalPanel.setLayout(
new BoxLayout(verticalPanel, BoxLayout.Y_AXIS));
Component verticalStrut =
Box.createVerticalStrut(VERTICAL_STRUT_SIZE);
verticalPanel.add(verticalStrut);
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
45
Display 14.13
BoxLayout
(4/5)
JButton vStopButton = new JButton("Red");
vStopButton.addActionListener(this);
verticalPanel.add(vStopButton);
Component verticalStrut2 =
Box.createVerticalStrut(VERTICAL_STRUT_SIZE);
verticalPanel.add(verticalStrut2);
JButton vGoButton = new JButton("Green");
vGoButton.addActionListener(this);
verticalPanel.add(vGoButton);
content.add(verticalPanel, BorderLayout.EAST);
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
46
Display 14.13
BoxLayout
(5/5)
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Red"))
colorPanel.setBackground(Color.red);
else if (e.getActionCommand().equals("Green"))
colorPanel.setBackground(Color.green);
else
System.out.println("Error in button interface.");
}
public static void main(String[] args)
{
BoxLayoutDemo gui = new BoxLayoutDemo();
gui.setVisible(true);
}
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
47
Execution Result of
BoxLayoutDemo.java
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
48
Display 14.14
Box Container Class
(1/4)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BoxClassDemo extends JFrame implements ActionListener
{
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
public static final int HORIZONTAL_STRUT_SIZE = 15;
public static final int VERTICAL_STRUT_SIZE = 10;
private JPanel colorPanel;
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
49
public BoxClassDemo()
{
setSize(WIDTH, HEIGHT);
addWindowListener(new WindowDestroyer());
setTitle("Box Demonstration");
Display 14.14
Container content = getContentPane();
Box Container Class
content.setLayout(new BorderLayout());
(2/4)
colorPanel = new JPanel();
colorPanel.setBackground(Color.blue);
content.add(colorPanel, BorderLayout.CENTER);
//Horizontal buttons at bottom of frame:
Box horizontalBox = Box.createHorizontalBox();
Component horizontalStrut =
Box.createHorizontalStrut(HORIZONTAL_STRUT_SIZE);
horizontalBox.add(horizontalStrut);
JButton hStopButton = new JButton("Red");
hStopButton.addActionListener(this);
horizontalBox.add(hStopButton);
Component horizontalStrut2 =
Box.createHorizontalStrut(HORIZONTAL_STRUT_SIZE);
horizontalBox.add(horizontalStrut2);
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
50
JButton hGoButton = new JButton("Green");
hGoButton.addActionListener(this);
horizontalBox.add(hGoButton);
content.add(horizontalBox, BorderLayout.SOUTH);
//Vertical buttons on right side of frame:
Box verticalBox = Box.createVerticalBox();
Display 14.14
Component verticalStrut =
Box Container Class
Box.createVerticalStrut(VERTICAL_STRUT_SIZE);
(3/4)
verticalBox.add(verticalStrut);
JButton vStopButton = new JButton("Red");
vStopButton.addActionListener(this);
verticalBox.add(vStopButton);
Component verticalStrut2 =
Box.createVerticalStrut(VERTICAL_STRUT_SIZE);
verticalBox.add(verticalStrut2);
JButton vGoButton = new JButton("Green");
vGoButton.addActionListener(this);
verticalBox.add(vGoButton);
content.add(verticalBox, BorderLayout.EAST);
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
51
Display 14.14
Box Container Class
(4/4)
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Red"))
colorPanel.setBackground(Color.red);
else if (e.getActionCommand().equals("Green"))
colorPanel.setBackground(Color.green);
else
System.out.println("Error in button interface.");
}
public static void main(String[] args)
{
BoxClassDemo gui = new BoxClassDemo();
gui.setVisible(true);
}
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
52
Execution Result of
BoxClassDemo.java
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
53
Some Methods in the
CardLayout Manager Class
public void first(Container theContainer)
- Causes the first “card” in theContainer to be displayed.
 public void last(Container theContainer)
- Causes the last “card” in theContainer to be displayed.
 public void next(Container theContainer)
- Causes the next “card” in theContainer to be displayed.
- The next card is the one that was added after the currently displayed
“card” was added.
 public void previous(Container theContainer)
- Causes the previous “card” in theContainer to be displayed.
 public void show(Container theContainer,
String cardName)
- Displays the “card” that was added with the StringcardName as its
name.

Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
54
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
Display 14.15
CardLayout
(1/4)
public class CardLayoutDemo extends JFrame implements ActionListener
{
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
private CardLayout dealer;
private JPanel deckPanel;
public CardLayoutDemo()
{
setSize(WIDTH, HEIGHT);
addWindowListener(new WindowDestroyer());
setTitle("CardLayout Demonstration");
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
deckPanel = new JPanel();
dealer = new CardLayout();
deckPanel.setLayout(dealer);
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
55
JPanel startCardPanel = new JPanel();
startCardPanel.setLayout(new FlowLayout());
startCardPanel.setBackground(Color.lightGray);
JLabel startLabel = new JLabel("Hello");
startCardPanel.add(startLabel);
deckPanel.add("start", startCardPanel);
Display 14.15
CardLayout
(2/4)
JPanel greenCardPanel = new JPanel();
greenCardPanel.setLayout(new FlowLayout());
greenCardPanel.setBackground(Color.green);
JLabel goLabel = new JLabel("Go");
greenCardPanel.add(goLabel);
deckPanel.add("green", greenCardPanel);
JPanel redCardPanel = new JPanel();
redCardPanel.setLayout(new FlowLayout());
redCardPanel.setBackground(Color.red);
JLabel stopLabel = new JLabel("Stop");
redCardPanel.add(stopLabel);
deckPanel.add("red", redCardPanel);
contentPane.add(deckPanel, BorderLayout.CENTER);
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
56
Display 14.15
CardLayout
(3/4)
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.white);
buttonPanel.setLayout(new FlowLayout());
JButton stopButton = new JButton("Red");
stopButton.addActionListener(this);
buttonPanel.add(stopButton);
JButton goButton = new JButton("Green");
goButton.addActionListener(this);
buttonPanel.add(goButton);
JButton resetButton = new JButton("Reset");
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
contentPane.add(buttonPanel, BorderLayout.SOUTH);
dealer.first(deckPanel);//Optional
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
57
Display 14.15
CardLayout
(4/4)
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if (actionCommand.equals("Red"))
dealer.show(deckPanel, "red");
else if (actionCommand.equals("Green"))
dealer.show(deckPanel, "green");
else if (actionCommand.equals("Reset"))
dealer.show(deckPanel, "start");
else
System.out.println("Error in CardLayout Demo.");
}
public static void main(String[] args)
{
CardLayoutDemo demoGui = new CardLayoutDemo();
demoGui.setVisible(true);
}
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
58
Execution Result of
CardLayoutDemo.java
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
59
Display 14.17
Inner Class
(1/2)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class InnerClassDemo extends JFrame
{
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
public static void main(String[] args)
{
InnerClassDemo sampleGUI = new InnerClassDemo();
sampleGUI.setVisible(true);
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
60
public InnerClassDemo()
{
setSize(WIDTH, HEIGHT);
setTitle("Inner Class Demo");
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
Display 14.17
Inner Class
(2/2)
JLabel label = new JLabel(
"Please don't click that button!");
contentPane.add(label, BorderLayout.CENTER);
addWindowListener(new InnerDestroyer());
}
//An inner class with the same functionality
//as the class WindowDestroyer.
private class InnerDestroyer extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
61
Execution Result of
InnerClassDemo.java
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
62
The WindowListener Interface



Chapter 14
For a class to be a listener for window events, it must
implement the WindowListener interface.
By implementing the WindowListener interface, a
window can be its own listener.
The advantage of making a window its own listener is
that it is easy to call methods from the listener since
they are in the same object.
Java: an Introduction to Computer Science & Programming - Walter Savitch
63
The WindowListener Interface

Implementation of the WindowListener interface requires
these seven methods to be defined:
» public void windowOpened(WindowEvent e)
» public void windowClosing(WindowEvent e)
» public void windowClosed(WindowEvent e)
» public void windowIconified(WindowEvent e)
» public void windowDeiconified(WindowEvent e)
» public void windowActivated(WindowEvent e)
» public void windowDeactivated(WindowEvent e)

If a method will be not be used, it should be defined with an
empty body
WindowAdapter is a class that implements all seven methods
of the WindowListener with empty bodies.

Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
64
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
Display 14.19
WindowListener
(1/3)
public class WindowListenerDemo extends JFrame
implements ActionListener, WindowListener
{
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
public static void main(String[] args)
{
WindowListenerDemo demoWindow = new WindowListenerDemo();
demoWindow.setVisible(true);
}
public WindowListenerDemo()
{
setSize(WIDTH, HEIGHT);
addWindowListener(this);
setTitle("Window Listener Demonstration");
Container content = getContentPane();
content.setBackground(Color.blue);
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
65
content.setLayout(new FlowLayout());
JButton stopButton = new JButton("Red");
stopButton.addActionListener(this);
content.add(stopButton);
Display 14.19
WindowListener
(2/3)
JButton goButton = new JButton("Green");
goButton.addActionListener(this);
content.add(goButton);
}
public void actionPerformed(ActionEvent e)
{
Container content = getContentPane();
if (e.getActionCommand().equals("Red"))
content.setBackground(Color.red);
else if (e.getActionCommand().equals("Green"))
content.setBackground(Color.green);
else
System.out.println("Error in WindowListenerDemo.");
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
66
public void windowOpened(WindowEvent e)
{}
public void windowClosing(WindowEvent e)
{
this.dispose();
System.exit(0);
}
Display 14.19
WindowListener
(3/3)
public void windowClosed(WindowEvent e)
{}
public void windowIconified(WindowEvent e)
{}
public void windowDeiconified(WindowEvent e)
{}
public void windowActivated(WindowEvent e)
{}
public void windowDeactivated(WindowEvent e)
{}
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
67
Execution Result of
WindowListenerDemo.java
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
68
Programming the Close-Window
Button



The WindowListener interface can be used to program the
close-window button.
If the close-window button is not programmed, by default it will
close the window but not exit the program.
For a window that does not close when the close-window button
is clicked, use a method call like this:
setDefaultCloseOperation(
WindowConstants.DO_NOTHING_ON_CLOSE);


Chapter 14
The CloseWindowDemo uses this method call
When the close-window button is clicked, the program displays
a confirmation dialog instead of closing the window.
Java: an Introduction to Computer Science & Programming - Walter Savitch
69
CloseWindowDemo Program
Prevents window from closing so
public CloseWindowDemo()
that user can confirm or cancel
{
before window is closed.
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(
WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new InnerDestroyer());
setTitle("Close Window Demo");
Defined
Container contentPane = getContentPane();
on next
contentPane.setLayout(new BorderLayout()); slide
. . .
}
Constructor for the CloseWindowDemo
class, which inherits from JFrame.
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
70
CloseWindowDemo Program
Definition of inner class
used as listener for the
CloseWindowDemo class.
Inherits from WindowAdapter so
it does not have to define all seven
window event methods.
private class InnerDestroyer extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
ConfirmWindow askWindow = new ConfirmWindow();
askWindow.setVisible(true);
}
ConfirmWindow closes window and
}
exits program if user confirms close.
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
71
CloseWindowDemo Program
actionPerformed method from the
ConfirmWindow inner class
The main window
will only be
closed if the user
clicks the “Yes”
button in the
ConfirmWindow
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Yes"))
System.exit(0);
else if (e.getActionCommand().equals("No"))
dispose(); //Destroys only the ConfirmWindow.
else
System.out.println("Error in Confirm Window.");
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
72
import javax.swing.*;
Display 14.20
import java.awt.*;
CloseWindowDemo
import java.awt.event.*;
(1/4)
public class CloseWindowDemo extends JFrame
{
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
public static void main(String[] args)
{
CloseWindowDemo gui = new CloseWindowDemo();
gui.setVisible(true);
}
public CloseWindowDemo()
{
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(
WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new InnerDestroyer());
setTitle("Close Window Demo");
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
JLabel message = new JLabel(
"Please don't click that button.");
contentPane.add(message, BorderLayout.CENTER);
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
73
//Displays a window that checks if the user wants to exit.
private class InnerDestroyer extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
ConfirmWindow askWindow = new ConfirmWindow();
askWindow.setVisible(true);
Display 14.20
}
CloseWindowDemo
(2/4)
}
//Designed to be used with the inner class InnerDestroyer in
//the class CloseWindowDemo. Checks if the user wants to exit.
private class ConfirmWindow extends JFrame
implements ActionListener
{
public static final int WIDTH = 200;
public static final int HEIGHT = 100;
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
74
Display 14.20
public ConfirmWindow()
CloseWindowDemo
{
(3/4)
setSize(WIDTH, HEIGHT);
Container confirmContent = getContentPane();
confirmContent.setBackground(Color.white);
confirmContent.setLayout(new BorderLayout());
JLabel msgLabel = new JLabel(
"Are you sure you want to exit?");
confirmContent.add(msgLabel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
JButton exitButton = new JButton("Yes");
exitButton.addActionListener(this);
buttonPanel.add(exitButton);
JButton cancelButton = new JButton("No");
cancelButton.addActionListener(this);
buttonPanel.add(cancelButton);
confirmContent.add(buttonPanel, BorderLayout.SOUTH);
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
75
Display 14.20
CloseWindowDemo
(4/4)
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Yes"))
System.exit(0);
else if (e.getActionCommand().equals("No"))
dispose();//Destroys only the ConfirmWindow.
else
System.out.println("Error in Confirm Window.");
}
}
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
76
Execution Result of
CloseWindowDemo.java
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
77
Changing Components



Chapter 14
A program can add or remove components after a
GUI has been displayed, but that is beyond the scope
of the book.
Making components visible or not visible gives a
similar effect.
The setVisible method is used in the
VisibleDemo program to make only one of the red
and green labels visible at a time.
(code on next slide)
Java: an Introduction to Computer Science & Programming - Walter Savitch
78
Changing Components
The actionPerformed method from the VisibleDemo program
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals(“Red”))
{
colorPanel.setBackground(Color.red);
stopLabel.setVisible(false);
goLabel.setVisible(true); There is similar code for
validate();
when the Green button is
Visibility changes won’t
pressed, which turns the
}
occur until the validate
background green and
. . .
method is called.
hides the go label.
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
79
import
import
import
public
javax.swing.*;
Display 14.21
java.awt.*;
Invisible Labels
(1/3)
java.awt.event.*;
class VisibilityDemo extends JFrame
implements ActionListener
{
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
private JLabel upLabel;
private JLabel downLabel;
public VisibilityDemo()
{
setSize(WIDTH, HEIGHT);
addWindowListener(new WindowDestroyer());
setTitle("Visibility Demonstration");
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.setBackground(Color.white);
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
80
upLabel = new JLabel("Here I am up here!");
contentPane.add(upLabel, BorderLayout.NORTH);
upLabel.setVisible(false);
downLabel = new JLabel("Here I am down here!");
contentPane.add(downLabel, BorderLayout.SOUTH);
downLabel.setVisible(false);
Display 14.21
Invisible Labels
(2/3)
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.white);
buttonPanel.setLayout(new FlowLayout());
JButton upButton = new JButton("Up");
upButton.addActionListener(this);
buttonPanel.add(upButton);
JButton downButton = new JButton("Down");
downButton.addActionListener(this);
buttonPanel.add(downButton);
contentPane.add(buttonPanel, BorderLayout.CENTER);
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
81
public void actionPerformed(ActionEvent e)
Display 14.21
{
Invisible Labels
if (e.getActionCommand().equals("Up"))
(3/3)
{
upLabel.setVisible(true);
downLabel.setVisible(false);
validate();
}
else if (e.getActionCommand().equals("Down"))
{
downLabel.setVisible(true);
upLabel.setVisible(false);
validate();
}
else
System.out.println("Error in VisibilityDemo interface.");
}
public static void main(String[] args)
{
VisibilityDemo demoGui = new VisibilityDemo();
demoGui.setVisible(true);
}
}
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
82
Execution Result of
VisibilityDemo.java
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
83
Another Look at the Swing Class Hierarchy
JComponent
Swing
AbstractButton
JLabel
JMenuBar
JMenuItem
Abstract Class
Class
JButton
JMenu




All of the basic properties of JButton and JMenuItem are inherited
from AbstractButton.
JButton and JMenuItem are similar because they are derived from
the same abstract class.
Since AbstractButton is an abstract class, no objects of that class
can be made.
The purpose of the AbstractButton class is to provide a place for
code that is common to JButton and JMenuItem and avoid repeated
code.
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
84
Another Look at the Swing Class Hierarchy
JComponent
Swing
AbstractButton
JLabel
JMenuBar
JMenuItem
Abstract Class
Class
JButton
JMenu




JLabel and JButton inherit from a common ancestor, namely
Jcomponent, so they have some similarities.
Notice, however, that JLabel and JButton are not derived from the
same class, even though they have a common ancestor.
The hierarchy reflects the fact that JButton and JMenuItem are more
similar than JLabel and JButton.
Also notice that JMenu inherits from JMenuItem, so it can be used
anywhere a JMenuItem can. This allows nested menus.
Chapter 14
Java: an Introduction to Computer Science & Programming - Walter Savitch
85
Summary








Chapter 14
You can add icons to JButtons, JLabels, and JMenuItems.
A JMenuBar can be added to a JFrame with the method
setJMenuBar or with the usual add method.
Both buttons and menu items fire action events and so should have
an ActionListener registered with them.
You can use the class JScrollPane to add scroll bars to a text area.
You can define a window listener class by having it implement the
WindowListener interface.
When you define a GUI using Swing you can specify the look and feel
for the GUI.
If you want a close-button to do something other than close the
window, you must use SetDefaultCloseOperation.
If you change the visibility of a component you should use the
validate method to update the GUI.
Java: an Introduction to Computer Science & Programming - Walter Savitch
86