22 GUIProgramming
22 GUIProgramming
AWT Classes
Although new versions of most of the components have been
provided, many of the classes and interfaces in the AWT are still
used for GUI programming.
Component, Container, Color, Font, FontMetrics, EventObject,
the event classes, the event listener interfaces, and others.
Swing
Version 1.2 of Java has extended the AWT with the Swing Set,
which consists of lightweight components that can be drawn
directly onto containers using code written in Java.
"North"
"South"
Creating a JFrame
JFrame jf = new JFrame("title"); // or JFrame()
jf.setSize(300, 200); // width, height in pixels (required)
jf.setVisible(true); // (required)
jf.setTitle("New Title");
jf.setLocation(50, 100); // x and y from upper-left corner
Green Frame
x
height
increasing y
width
Placing Components
Container cp = jf.getContentPane();
cp.add(c1, "North");
cp.add(c2, "South");
or cp.add(c1, BorderLayout.NORTH);
// Java has five constants like this
The constant BorderLayout.NORTH has the value "North".
JPanel
An invisible Container used to hold components or to draw on.
• Uses FlowLayout by default (left-to-right, row-by-row).
obj 7
30 pixels
Line of text.
50 pixels
Example
Write four lines of text on a panel that is placed on a frame.
The lines illustrate different fonts.
import java.awt.*;
import javax.swing.*;
class FontPanel extends JPanel
{
FontPanel()
{ setBackground(Color.white);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g); // clear background
g.setFont(new Font("Serif", Font.BOLD, 12));
g.drawString("Serif 12 point bold.", 20, 50 );
g.setFont(new Font("Monospaced", Font.ITALIC, 24));
g.drawString("Monospaced 24 point italic.", 20, 100);
JButton
Buttons are components that can be placed on a container.
• Can have a String label on them.
JButton b = new JButton("Click");
add(b); // assuming FlowLayout
b.setLabel("Press");
String s = b.getLabel();
Example
Prompt user to press a button and then display result
as a Label.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonTest extends JFrame
{
private JLabel result;
ButtonTest()
{
setTitle("ButtonTest");
JLabel lab = new JLabel("Click one of the buttons.");
getContentPane().add(lab, "North");
result = new JLabel(" ");
getContentPane().add(result, "South");
JButton yes = new JButton("Yes");
getContentPane().add(yes, "West");
yes.addActionListener(new YesHandler());
JButton no = new JButton("No");
getContentPane().add(no, "East");
no.addActionListener(new NoHandler());
}
Note that clicking the close box of the window does not
terminate the program, although in Swing the window
disappears.
We need to write code that recognizes the event fired when the
window is closed and shuts down the program.
Adapters
Observe the large number of methods that need to be
implemented in the WindowHandler, even though only
one of the methods does anything.
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{ System.exit(0); }
} );
Listener Interfaces
The table below shows the number of methods in some
of the interfaces and the name of the corresponding adapter,
if there is one.
java.awt.event
ActionListener
actionPerformed(ActionEvent e)
ItemListener
itemStateChanged(ItemEvent e)
MouseListener
mousePressed(MouseEvent e)
mouseReleased(MouseEvent e)
mouseEntered(MouseEvent e)
mouseExited(MouseEvent e)
mouseClicked(MouseEvent e)
MouseMotionListener
mouseDragged(MouseEvent e)
mouseMoved(MouseEvent e)
KeyListener
keyPressed(KeyEvent e)
keyReleased(KeyEvent e)
keyTyped(KeyEvent e)
AdjustmentListener
adjustmentValueChanged(AdjustmentEvent e)
javax.swing.event
ChangeListener
stateChanged(ChangeEvent e)
ListSelectionListener
valueChanged(ListSelectionEvent e)
Text fields allow the user to enter text that can be processed
by the program.
One constructor takes an int representing the width of the field
in characters (approximately). Others take an initial string as a
parameter or both.
JTextField tf1 = new JTextField(10);
JTextField tf2 = new JTextField("Message");
add(tf1);
add(tf2);
tf1.setText("New Message");
String s = tf2.getText();
tf2.setEditable(false); // default is true
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextFieldTest extends JFrame
implements ActionListener
{
TextFieldTest()
{
setTitle("TextFieldTest");
addWindowListener(new WindowHandler());
Container cp = getContentPane();
cp.setLayout(new FlowLayout()); // override default
1 2 3 4
5 6 7 8
Example: TextFieldTest
cp.setLayout(new GridLayout(6,1));
/*****************************************************************
// Instance method getActionCommand for an ActionEvent
// returns the String label of component that caused the event.
public void actionPerformed(ActionEvent evt)
{
String arg = evt.getActionCommand();
if (arg.equals("Yellow"))
jp.setBackground(Color.yellow);
else if (arg.equals("Cyan"))
jp.setBackground(Color.cyan);
yellow.addActionListener(new BH(Color.yellow));
:
cyan.addActionListener(new BH(Color.cyan));
:
magenta .addActionListener(new BH(Color.magenta));
:
Example
Place two check boxes on a frame and record their state in a
label message.
As a shorthand, we use the frame class as the ItemListener.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Radio Buttons
Similar to check boxes, except that only one button in a group
may be checked at a time.
hot = new JRadioButton("Hot", false);
warm = new JRadioButton("Warm", true);
cold = new JRadioButton("Cold", false);
ButtonGroup gp = new ButtonGroup();
gp.add(hot);
gp.add(warm);
gp.add(cold);
The box for warm is the selected one, initially.
Menus
Menus are placed on a menu bar, which is attached to a frame.
JMenuBar mb = new JMenuBar();
JMenu file = new JMenu("File");
file.add(new JMenuItem("New")); // no way to add
file.add(new JMenuItem("Open")); // listeners
mb.add(file);
JMenu edit = new JMenu("Edit");
edit.add(copy = new JMenuItem("Copy"));
edit.add(paste = new JMenuItem("Paste"));
edit.addSeparator();
edit.add(clear = new JMenuItem("Clear"));
mb.add(edit);
jf.setJMenuBar(mb); // assumes jf is a JFrame
Menu Events
Selecting a menu item triggers an ActionEvent that can be
handled by an ActionListener that must be register with each
menu item that it plans to cover.
If ae is the ActionEvent sent by some menu item, it can be
decoded using the following commands:
Object jmi = ae.getSource();
if (jmi == clear) handleClear();
or
String arg = ((JMenuItem)jmi).getText();
36 GUI Programming Copyright 2004 by Ken Slonneger
if (arg.equals("Clear")) handleClear();
Example
Put three radio buttons at the top of a frame that changes color
according to the button chosen.
Also provide a menu that allows the color to be picked.
Have the buttons denote the selected color for consistency.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class RadioButtonFrame extends JFrame
implements ActionListener
{
RadioButtonFrame()
{
setTitle("Radio Buttons");
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{ System.exit(0);
}
} );
topPanel = new JPanel();
ButtonGroup g = new ButtonGroup();
cyanButton = addRadioButton(topPanel, g, "Cyan", false);
yellowButton = addRadioButton(topPanel, g, "Yellow", false);
magentaButton =
addRadioButton(topPanel, g, "Magenta", false);
Alternative Construction
Object [] items = { "private", "protected", "default", "public" };
JComboBox scope = new JComboBox(items);
Methods
lang.setVisibleRowCount(2);
lang.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
lang.addListSelectionListener(new ListHandler());
Selection Choices
ListSelectionModel.SINGLE_SELECTION
ListSelectionModel.SINGLE_INTERVAL_SELECTION
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION (default)
Selections
Click: single selection
Control-click: additional selection
Shift-click: contiguous range
Example
Use a JComboBox to set the color of a group of words chosen
from a JList object and displayed on a panel.
Draw the words on the panel via Graphics object associated with it.
Provide an ActionListener for the JComboBox and a
ListSelectionListener for the JList.
Both the JList and JComboBox are placed in the East region using
a vertical BoxLayout, which lets them have their natural height.
The words are drawn on a subclass Show of JPanel, which is placed
in the center of the frame.
Copyright 2004 by Ken Slonneger GUI Programming 43
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class States extends JFrame
implements ActionListener, ListSelectionListener
{
States()
{
setTitle("States");
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox choice = new JComboBox();
choice.addItem("Red"); choice.addItem("Orange");
choice.addItem("Green"); choice.addItem("Black");
choice.addItem("Blue"); choice.addItem("Cyan");
choice.addActionListener(this);
String [] items = { "Illinois", "Indiana", "Iowa", "Michigan",
"Minnesota", "Ohio", "Pennsylvania", "Wisconsin" };
JList words = new JList(items);
JScrollPane sPane = new JScrollPane(words);
words.addListSelectionListener(this);
JPanel jp = new JPanel();
jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS));
jp.add(sPane); jp.add(choice);
getContentPane().add(jp, "East");
show = new Show();
show.setBackground(Color.white);
getContentPane().add(show, "Center");
}
Dynamic JLists
To have a JList change during the execution of a program,
we must deal with its underlying model, which contains the
actual data.
Example
• Create a model for a list
DefaultListModel model = new DefaultListModel();
Drawing on a Panel
Variations of mouseDown
• Click
• Shift-click
• Double-click
Uses of mouseDrag
• Draw a line (draw)
• Draw a filled oval (erase)
// Constructors
public Point(); // (0, 0)
public Point(int x, int y);
public Point(Point p);
// Methods
public boolean equals(Object obj);
public void move(int nx, int ny);
public String toString();
public void translate(int dx, int dy);
}
Note
The drawing color can be set by two different methods:
setColor(Color c) in the class Graphics
setForeground(Color c) in the class Component
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Doodle extends JFrame
{
private Point lineStart = new Point(0,0);
private int size = 16; // erasing width
private DrawPanel panel;
Doodle()
{
setTitle("Doodle");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addMouseListener(new Down());
addMouseMotionListener(new Drag());
panel = new DrawPanel();
panel.setBackground(Color.cyan);
getContentPane().add(panel);
}
JTextArea
Constructors
JTextArea(int rows, int cols)
JTextArea(String text, int rows, int cols)
Problem: Print strings from a String array sArr into a text area.
JTextArea lines = new JTextArea("", 10, 60);
for (int k=0; k< sArr.length; k++)
lines.append(sArr[k] + "\n");
A Password Field
Suppose we need a text field for entering a password.
As characters are typed in the field, we do not want them
to be visible.
Solution: JPasswordField, a subclass of JTextField.
Constructors
JPasswordField()
JPasswordField(String s)
Example
JPasswordField jpf =
new JPasswordField("Enter your password here");
Sample Code
This program has a password field on a frame.
When return is typed in the field, it compares the string typed
with a predefined password, “herky”.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JPApp extends JFrame
{
private String pw = "herky";
private JPasswordField pwField;
private JLabel ans;