ch17 NN
ch17 NN
ch17 NN
GUI Overview
Event-Driven Programming Basics
GUI Classes and Packages
A Simple Window Program
JFrame Class
Java Components
JLabel Component
JTextField Component
Component Listeners
Interfaces
Inner Classes
Anonymous Inner Classes
JButton Component
JOptionPane Dialog Box
Distinguishing Between Multiple Events
Using getActionCommand to Distinguish Between Multiple Events
(optional)
Color
Chapter 17 2
GUI Programming Basics
Mouse Listeners
MouseListener Interface
MouseMotionListener Interface
Mouse Adapter Classes
DragSmiley Program
Displaying an Image
3
GUI Overview
GUI stands for Graphical User Interface.
Graphical = picture objects (windows, buttons, menus, etc.)
User = the person who uses the program.
Interface = the manner in which the user interacts with the
program.
Although companies still write text-based programs
for internal use, most companies write GUI-based
programs for programs that are to be used externally.
4
Event-Driven Programming Basics
GUI programs usually use event-driven programming
techniques.
Basic idea behind event-driven programming:
The program waits for events to occur and then it responds.
An event is a message that tells the program that
something has happened. For example, if the user
clicks a button, then an event is generated, and it
tells the program that a particular button was clicked.
More formally, when the user clicks a button, we say
that the button object fires an event.
5
Event-Driven Programming Basics
Note these additional event examples:
------------------
OK -----------------
-------------------
---------------
------------------
------------------
-----------------
8
GUI Classes and Packages
In writing a GUI program, use Java's pre-built GUI classes. For
example:
Use the pre-built JButton class when you need a button.
Use the pre-built Color class when you need to specify a color.
In the first Java compiler, JDK 1.0, all GUI classes were bundled
into one library known as the Abstract Windowing Toolkit (AWT).
The AWT's component classes were less than ideal in terms of
portability, so Sun developed a set of more-portable GUI
components and put them in a new GUI library named Swing.
The Swing library adds lots of functionality to the AWT, but it
does not replace the AWT entirely.
Today, Java GUI application programmers use both libraries -
Swing and the AWT.
The primary Swing package is javax.swing. The primary AWT
packages are java.awt and java.awt.event. Get used to
importing those three packages in all of your GUI programs.
9
A Simple Window Program
import javax.swing.*; // for JFrame & JLabel
import java.awt.*; // for FlowLayout
public class SimpleWindow extends JFrame
{
private static final int WIDTH = 300;
private static final int HEIGHT = 200;
public SimpleWindow()
{
setTitle("Simple Window");
setSize(WIDTH, HEIGHT);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
createContents();
setVisible(true);
} // end SimpleWindow constructor
private void createContents()
{
JLabel label = new JLabel("Hi! I'm Larry the label!");
add(label);
} // end createContents
public static void main(String[] args)
{
new SimpleWindow();
} // end main
} // end class SimpleWindow
12
JFrame Class
The JFrame class:
Should be used as the superclass for most of your GUI
application windows, so programmer-defined windows should
extend the JFrame class.
Is in the javax.swing package, so import that package.
(As explained in Chapter 5, you can use an * as a wildcard to
import all the classes within a particular package.)
Is called a container class because:
It contains things (like labels, buttons, menus, etc).
It's derived from the Container class.
Implements all the standard window features such as:
a border, a title bar, a minimize button, a close-window button
(the "X"), the ability to resize the window, etc.
13
JFrame Class
JFrame methods:
setTitle - Displays a title in the current window.
setSize - Sets the width and height dimensions in pixels of
the current window.
Your monitor will be set to a certain number of pixels (e.g.,
800x600, 1024x768, etc.). The pixel setting is called the
resolution. A pixel is a monitor's smallest displayable unit.
Example:
nameBox.addActionListener(
new ActionListener()
ActionListener is an interface
{
public void actionPerformed(ActionEvent e)
{
...
30
JButton Component
Button component interface:
A button component acts like a real-world button - when
you press/click it, something happens.
3. The JButton class and the add method are both in the
javax.swing package so import that package.
31
JButton Component
How to implement a button (continued):
4. Implement a listener class that includes an
actionPerformed event handler method:
private class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
<do something>
}
}
5. Register your button-listener object:
helloButton.addActionListener(new Listener());
32
JButton Component
Here are API headings and descriptions for some of
the more popular JButton methods :
public String getText()
Returns the button's label.
public void setText(String text)
Assigns the button's label.
public void setVisible(boolean flag)
Makes the button visible or invisible.
public void addActionListener(ActionListener listener)
Adds a listener to the button. The listener "listens" for the
button being clicked.
33
When the user 1) clicks the button or 2) presses enter in the input text box,
the entered number's factorial displays in the output text box.
//*******************************
34
Factorial Button Program
//*********************************** if (x < 0)
{
// Inner class for event handling. xfBox.setText("undefined");
}
private class Listener implements else
ActionListener {
{ if (x == 0 || x == 1)
public void {
actionPerformed(ActionEvent e) xf = 1;
{ }
int x; // user entered number else
int xf; // x factorial {
xf = 1;
try for (int i=2; i<=x; i++)
{ {
x = Integer.parseInt( xf *= i;
xBox.getText()); }
} } // end else
catch (NumberFormatException nfe)
{ xfBox.setText(
x = -1; // indicates invalid x Integer.toString(xf));
} } // end else
} // end actionPerformed
All GUI I/O is string-based. Use parseInt } // end class Listener
to convert string input to an integer.
35
Factorial Button Program
//**************************************
Example:
JOptionPane.showMessageDialog(null,
"Click factorial button to perform calculation.");
37
JOptionPane Dialog Box
JOptionPane's showMessageDialog method is a
class method so call it using <class-name> dot
syntax.
showMessageDialog's first argument specifies the
position of the dialog box. If the argument is null,
the dialog box appears in the center of the screen.
The JOptionPane class is in the javax.swing
package so import that package.
38
Distinguishing Between Multiple Events
When the user presses enter in the input text box, a warning dialog box is displayed.
content pane
//**************************************
import javax.swing.*;
//**************************************
56
DragSmiley Program
public DragSmiley()
{
setTitle("Drag Smiley");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
smileyPanel = new SmileyPanel();
add(smileyPanel);
setVisible(true);
} // end DragSmiley constructor
//**************************************
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public SmileyPanel()
{
image = SMILEY;
imageCorner = new Point(0, 0); // image starts at top left
ClickListener clickListener = new ClickListener();
DragListener dragListener = new DragListener();
this.addMouseListener(clickListener);
this.addMouseMotionListener(dragListener);
} // end SmileyPanel constructor
//**************************************
Where:
The <image-observer> argument refers to an object that listens
for the completion of the image being loaded.
<top-left-x> refers to the x coordinate position of the image's
top-left corner.
<top-left-y> refers to the y coordinate position of the image's
top-left corner.
For example:
image.paintIcon(this, g, (int) imageCorner.getX(),
(int) imageCorner.getY());