June 16: GUI Components and Event Handling.

advertisement
Review
• Polymorphism
– “having many forms”
– Helps build extensible systems
• Dynamic/late binding
– Implements polymorphic processing of objects
– Use superclass reference to refer to subclass object
– Program chooses “correct” method in subclass at
execution
• Abstract Class
• Interface
1
Introduction to Graphics
• An appealing feature of Java
• Made easy by many standard library calls that are
not included in many languages
• With graphics one can easily draw shapes, one can
control colors and fonts, one can organize the
screen in a user-friendly way.
2
awt and swing
• Most of the GUI classes are provided in Java by
the Abstract Windowing Tools (AWT) package
(java.awt).
• AWT was expanded with the Swing classes
(javax.swing) in Java 2 platform
– Swing classes provide alternative components that have
more functionality than AWT
– We shall prefer using swing
• Part of the java class hierarchy structure
– Classes of AWT such Color, Font, Graphics,
Component are derived from the Object superclass.
3
Creating a window
• Top-level containers
– Window
• Jdialog
• Jframe
– Panel
• Japplet
• User-interface components are arranged by
placing them in a Swing Container object
– E.g. Jbutton, Jlabel, Jlist
4
Dialog by JOptionPane
• Several Swing component classes can directly
instantiate and display dialogs. E.g. JoptionPane
import javax.swing.*;
class MessageDialog {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null,"Hi, how are you?");
JOptionPane.showMessageDialog(null, "Show second dialog
message.");
}
}
5
Dialog by JOptionPane
• Another JOptionPane example
import javax.swing.JOptionPane;
public class DialogDemo {
public static void main(String[] args) {
String ans;
ans = JOptionPane.showInputDialog(null,
"Speed in miles per hour?");
double mph = Double.parseDouble(ans);
double kph = 1.621 * mph;
JOptionPane.showMessageDialog(null, "KPH = " + kph);
System.exit(0);
}
}
6
Frame Windows: An Example
import javax.swing.*;
public class EmptyFrameViewer{
public static void main(String[] args) {
JFrame frame = new JFrame();
final int FRAME_WIDTH = 300;
final int FRAME_HEIGHT = 300;
frame.setBounds(100, 100, FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("An Empty Frame");
//Makes the frame perform the given action when it
closes.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//make a frame appear on the screen after creating it
(default is invisible)
frame.setVisible(true);
}
}
7
Jframe: Commonly used constructors and
methods
• public JFrame() or public JFrame(String title)
– Creates a frame with an optional title.
•
•
•
•
•
setBounds(int x,int y,int width,int height)
setSize(int width,int height)
setBackground(Color c)
setVisible(boolean b):
pack()
– Resizes the frame to fit the components inside it
• setTitle(String name)
• getTitle()
• setResiable(boolean m)
8
Applets Review
• Can be executed by any web browser that supports
Java, or Java AppletViewer
– Not a stand-alone application (cf. JFrame)
– sizing and creation of the window is done in HTML instead
of Java
// this is the file EmptyAppletViewer.html
<html>
<applet code = "EmptyAppletViewer.class" width = "400" height = "130">
</applet>
</html>
– In this course, always use the JDK appletviewer
• appletviewer ShowColors.html
9
Applets : A basic Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EmptyAppletViewer extends JApplet {
public void paint( Graphics g )
{
// call superclass's paint method
super.paint( g );
// add further implementations here
}
}
10
Java’s Coordinate System Review
• Scheme for identifying all points on screen
• Upper-left corner has coordinates (0,0)
• Coordinate point composed of x-coordinate and ycoordinate
• Java coordinate system. Units are measured in
pixels. (0, 0)
+x
X a xis
xy
( , )
y
+
Y a xis
11
Swing Overview
• Swing GUI components
– Package javax.swing
– Components originate from AWT (package java.awt)
– Contain look and feel
• Appearance and how users interact with program
12
The class hierarchy
https://www3.ntu.edu.sg/home/ehchua/programming/java/J4a_GUI_2.html
13
Swing Overview (cont.)
• Class Component
– Contains method paint for drawing Component onscreen
• Class Container
– Collection of related components
– Contains method add for adding components
• Class JComponent
– Pluggable look and feel for customizing look and feel
– Shortcut keys (mnemonics)
– Common event-handling capabilities
14
The Component Class
• A superclass for many classes in AWT
• Its method paint() takes a Graphics object as
an argument:
public void paint (Graphics g)
• Derived classes from Component will override
paint() to perform various graphics operations
with the help of the g Graphics object passed as
a parameter.
public abstract class Component extends Object implements
ImageObserver, MenuContainer, Serializable
15
Graphics Context and Graphics Objects
• Graphics context
– Enables drawing on screen
– Graphics object manages graphics context
• Controls how information is drawn
– Class Graphics is abstract
• Cannot be instantiated
• Contributes to Java’s portability
– Class Component method paint takes Graphics object
public void paint( Graphics g )
– Called through method repaint
16
Color Control
• Class Color
– Defines methods and constants for manipulating colors
– Colors are created from red, green and blue components
• RGB values
– Color Class static constants
• Orange, pink, cyan, magenta, yellow, black, white, gray,
lightGray, darkGray, red, green, blue
– Color methods and color-related Graphics methods.
•
•
•
•
•
•
public Color( float r, float g, float b )
public int getRed()
// Color class
public int getGreen()
// Color class
public int getBlue()
public Color getColor()
public void setColor( Color c )
17
Graphics and Color Example: A Jframe Application
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class ShowColors extends JFrame {
// constructor sets window's title bar string and dimensions
public ShowColors()
{
super( "Using colors" ); // this will put a title on the frame bar
setSize( 400, 130 );
// size in pixels
show();
}
// draw rectangles and Strings in different colors
public void paint( Graphics g )
{
// call superclass's paint method
super.paint( g );
// setColor, fillRect, drawstring, getColor, getRed etc
// are methods of Graphics
// set new drawing color using integers for R/G/B
g.setColor( new Color( 255, 0, 0 ) );
g.fillRect( 25, 25, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 40 );
// set new drawing color using floats
g.setColor( new Color( 0.0f, 1.0f, 0.0f ) );
g.fillRect( 25, 50, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 65 );
18
// set new drawing color using static Color objects
g.setColor( Color.blue );
g.fillRect( 25, 75, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 90 );
// display individual RGB values
Color color = Color.magenta;
g.setColor( color );
g.fillRect( 25, 100, 100, 20 );
g.drawString( "RGB values: " + color.getRed() + ", " +
color.getGreen() + ", " + color.getBlue(), 130, 115 );
}
}
// execute application
public static void main( String args[] )
{
ShowColors application = new ShowColors();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
}
// end class ShowColors
19
Graphics and Color Example: A Japplet Application
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ShowColors extends JApplet {
public void paint( Graphics g )
{
// call superclass's paint method
super.paint( g );
// set new drawing color using integers
g.setColor( new Color( 255, 0, 0 ) );
g.fillRect( 25, 25, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 40 );
// set new drawing color using floats
g.setColor( new Color( 0.0f, 1.0f, 0.0f ) );
g.fillRect( 25, 50, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 65 );
// set new drawing color using static Color objects
g.setColor( Color.blue );
g.fillRect( 25, 75, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 90 );
// display individual RGB values
Color color = Color.magenta;
g.setColor( color );
g.fillRect( 25, 100, 100, 20 );
g.drawString( "RGB values: " + color.getRed() + ", " +
color.getGreen() + ", " + color.getBlue(), 130, 115 );
}
} // end class ShowColors
20
The class hierarchy of Swing's
JComponents
https://www3.ntu.edu.sg/home/ehchua/programming/java/J4a_GUI_2.html
21
Graphic User Interface (GUI) Components
• A Visual Guide to Swing Components
22
Most of the Swing Components supports
these features
• Text and icon.
• Keyboard short-cut
• Tool tips: display when the mouse-pointer pauses
on the component.
• Look and feel: customized appearance and user
interaction for the operating platform.
• Localization: different languages for different
locale.
23
Some Basic GUI Components
Component
JLabel
JTextField
Description
An area where uneditable text or icons can be displayed.
An area in which the user inputs data from the keyboard. The area can
also display information.
JButton
An area that triggers an event when clicked.
JCheckBox
A GUI component that is either selected or not selected.
JComboBox
A drop-down list of items from which the user can make a selection
by clicking an item in the list or possibly by typing into the box.
JList
An area where a list of items is displayed from which the user can
make a selection by clicking once on any element in the list.
Double-clicking an element in the list generates an action event.
Multiple elements can be selected.
JPanel
A container in which components can be placed.
Some basic GUI components.
24
JLabel
• Label
– Provide text on GUI
– Defined with class JLabel
– Can display:
• Single line of read-only text
• Image
• Text and image
25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// LabelTest.java
// Demonstrating the JLabel class.
// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class LabelTest extends JFrame {
private JLabel label1, label2, label3;
Declare three JLabels
// set up GUI
public LabelTest()
{
super( "Testing JLabel" );
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// JLabel constructor with a string argument
label1 = new JLabel( "Label with text" );
label1.setToolTipText( "This is label1" );
container.add( label1 );
// JLabel constructor with string, Icon and
// alignment arguments
Icon bug = new ImageIcon( "bug1.gif" );
label2 = new JLabel( "Label with text and icon",
bug, SwingConstants.LEFT );
label2.setToolTipText( "This is label2" );
container.add( label2 );
Building of GUI is done in
the constructor
Create first JLabel with
text “Label with text”
Tool tip is text that appears when
user moves cursor over JLabel
Create second JLabel
with text to left of image
26
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58 }
// JLabel constructor no arguments
label3 = new JLabel();
label3.setText( "Label with icon and text at bottom" );
label3.setIcon( bug );
label3.setHorizontalTextPosition( SwingConstants.CENTER );
label3.setVerticalTextPosition( SwingConstants.BOTTOM );
label3.setToolTipText( "This is label3" );
container.add( label3 );
Create third JLabel
with text below image
setSize( 275, 170 );
setVisible( true );
}
// execute application
public static void main( String args[] )
{
LabelTest application = new LabelTest();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
// end class LabelTest
27
Using images in GUI: ImageIcon
• javax.swing.ImageIcon class models an image
icon.
• The ImageIcon class implements javax.swing.Icon
interface, and hence, often upcasted and
referenced as Icon.
• An ImageIcon is a fixed-size picture, typically
small, and mainly used for decorating GUI
components.
• To construct an ImageIcon, provide the image
filename or URL.
• Image file type of GIF, PNG, JPG and BMP are
supported.
28
Layout Management
– Each container has a layout manager that directs the
arrangement of its components
– Components are added to a container which uses a
layout manager to place them
– Three useful layout managers are:
1) Border layout
2) Flow layout
3) Grid layout
Page 29
29
Jframe’s Content Pane
• A JFrame has a content pane which is a Container
where you can add components
– Use the getContentPane method to get its reference
Container container= getContentPane();
– Set laylout
container.setLayout( new FlowLayout() );
– Add components to the content pane
container.add( label1 );
Page 30
30
Event-Handling Model
• GUIs are event driven
– Generate events when user interacts with GUI
• e.g., moving mouse, pressing button, typing in text field, etc.
• Class java.awt.AWTEvent
31
Some event classes of package
java.awt.event
java.lang.Object
java.util.EventObject
java.awt.AWTEvent
ActionEvent
ContainerEvent
AdjustmentEvent
FocusEvent
ItemEvent
PaintEvent
ComponentEvent
WindowEvent
InputEvent
Ke y
Class nam e
Interfa c e nam e
KeyEvent
MouseEvent
32
Event-Handling Model (cont.)
• Event-handling model
– Three parts
• Event source
– GUI component with which user interacts
• Event object
– Encapsulates information about event that occurred
• Event listener
– Receives event object when notified, then responds
– Programmer must perform two tasks
• Register event listener for event source
• Implement event-handling method (event handler)
33
Event-listener interfaces of package
java.awt.event
ActionListener
java.util.EventListener
AdjustmentListener
ComponentListener
ContainerListener
FocusListener
ItemListener
KeyListener
MouseListener
MouseMotionListener
Key
C la ss na me
Inte rfa c e na me
TextListener
WindowListener
34
JTextField and JPasswordField
• JTextField
– Single-line area in which user can enter text
• JPasswordField
– Extends JTextField
– Hides characters that user enters
35
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// TextFieldTest.java
// Demonstrating the JTextField class.
// Java core packages
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class TextFieldTest extends JFrame {
private JTextField textField1, textField2, textField3;
private JPasswordField passwordField;
// set up GUI
public TextFieldTest()
{
super( "Testing JTextField and JPasswordField" );
Declare three
JTextFields and one
JPasswordField
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// construct textfield with default sizing
textField1 = new JTextField( 10 );
container.add( textField1 );
// construct textfield with default text
textField2 = new JTextField( "Enter text here" );
container.add( textField2 );
First JTextField
contains empty string
Second JTextField contains
text “Enter text here”
// construct textfield with default text and
// 20 visible elements and no event handler
textField3 = new JTextField( "Uneditable text field", 20Third
); JTextField
textField3.setEditable( false );
contains uneditable text
container.add( textField3 );
36
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// construct textfield with default text
passwordField = new JPasswordField( "Hidden text" );
container.add( passwordField );
// register event handlers
TextFieldHandler handler = new TextFieldHandler();
textField1.addActionListener( handler );
textField2.addActionListener( handler );
textField3.addActionListener( handler );
passwordField.addActionListener( handler );
setSize( 325, 100 );
setVisible( true );
JPasswordField contains
text “Hidden text,” but text
appears as series of asterisks (*)
Register GUI components with
TextFieldHandler
(register for ActionEvents)
}
// execute application
public static void main( String args[] )
{
TextFieldTest application = new TextFieldTest();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
Every TextFieldHandler
instance is an ActionListener
}
// private inner class for event handling
private class TextFieldHandler implements ActionListener {
// process text field events
public void actionPerformed( ActionEvent event )
{
String string = "";
// user pressed Enter in JTextField textField1
if ( event.getSource() == textField1 )
Method actionPerformed
invoked when user presses
Enter in GUI field
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94 }
string = "textField1: " + event.getActionCommand();
// user pressed Enter in JTextField textField2
else if ( event.getSource() == textField2 )
string = "textField2: " + event.getActionCommand();
// user pressed Enter in JTextField textField3
else if ( event.getSource() == textField3 )
string = "textField3: " + event.getActionCommand();
// user pressed Enter in JTextField passwordField
else if ( event.getSource() == passwordField ) {
JPasswordField pwd =
( JPasswordField ) event.getSource();
string = "passwordField: " +
new String( passwordField.getPassword() );
}
JOptionPane.showMessageDialog( null, string );
}
}
// end private inner class TextFieldHandler
// end class TextFieldTest
TextFieldTest.java
39
How Event Handling Works
• Two open questions
– How did event handler get registered?
• Answer:
– Through component’s method addActionListener
– Lines 43-46 of TextFieldTest.java
– How does component know to call actionPerformed?
• Answer:
– Event is dispatched only to listeners of appropriate type
– Each event type has corresponding event-listener interface
• Event ID specifies event type that occurred
40
Event registration for JTextField
textField1.
textField1
handler
JTextField
This is the
o bjec t. It c ontains a n
instanc e va riable o f typ e
E
ventListenerListthat
c alled
listenerList
it inherited from c lass
JComponent
.
listenerList
TextFieldHandler
This is the
o bjec t that imp lem ents
and define s
m ethod
.
ActionListener
actionPerformed
public void
actionPerformed(
ActionEvent event )
{
// event handled here
}
...
This refere nc e is c re ated by the stateme nt
textField1.addActionListener( handler );
41
JButton
• Button
– Component user clicks to trigger a specific action
– Several different types
•
•
•
•
Command buttons
Check boxes
Toggle buttons
Radio buttons
– javax.swing.AbstractButton subclasses
• Command buttons are created with class JButton
– Generate ActionEvents when user clicks button
42
The Button Hierarchy
javax.swing.JComponent
javax.swing.AbstractButton
javax.swing.JButton
javax.swing.ToggleButton
javax.swing.JCheckBox
javax.swing.JRadioButton
43
1 // ButtonTest.java
2 // Creating JButtons.
3
4 // Java core packages
5 import java.awt.*;
6 import java.awt.event.*;
7
8 // Java extension packages
9 import javax.swing.*;
10
Create two references
11 public class ButtonTest extends JFrame {
12
private JButton plainButton, fancyButton;
to JButton instances
13
14
// set up GUI
15
public ButtonTest()
16
{
17
super( "Testing Buttons" );
18
19
// get content pane and set its layout
20
Container container = getContentPane();
21
container.setLayout( new FlowLayout() );
22
23
// create buttons
Instantiate JButton with text
24
plainButton = new JButton( "Plain Button" );
25
container.add( plainButton );
26
27
Icon bug1 = new ImageIcon( "bug1.gif" );
Instantiate JButton with
28
Icon bug2 = new ImageIcon( "bug2.gif" );
29
fancyButton = new JButton( "Fancy Button", bug1 );
image and rollover image
30
fancyButton.setRolloverIcon( bug2 );
31
container.add( fancyButton );
32
Instantiate ButtonHandler
33
// create an instance of inner class ButtonHandler
34
// to use for button event handling
for JButton event handling
35
ButtonHandler handler = new ButtonHandler();
44
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64 }
fancyButton.addActionListener( handler );
plainButton.addActionListener( handler );
Register JButtons to receive
events from ButtonHandler
setSize( 275, 100 );
setVisible( true );
}
// execute application
public static void main( String args[] )
{
ButtonTest application = new ButtonTest();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
// inner class for button event handling
private class ButtonHandler implements ActionListener {
// handle button event
public void actionPerformed( ActionEvent event )
{
JOptionPane.showMessageDialog( null,
"You pressed: " + event.getActionCommand() );
}
}
When user clicks JButton,
ButtonHandler invokes
method actionPerformed
of all registered listeners
// end private inner class ButtonHandler
// end class ButtonTest
45
ButtonTest.java
46
Some Other Components
• State buttons
– On/Off or true/false values
– JToggleButton, JCheckBox, and
JRadioButton
• JComboBox (drop-down list)
– List of items from which user can select
• Jlist
– Single selection and Multiple Selection
• JTextArea and JTextField
– Multiple lines vs. single line
Examples are shown in the last lecture
Mouse Event Handling
• Event-listener interfaces for mouse events
– MouseListener
– MouseMotionListener
– Listen for MouseEvents
MouseListener and
MouseMotionListener interface methods
MouseListener and MouseMotionListener interface methods
Methods of interface MouseListener
public void mousePressed( MouseEvent event )
Called when a mouse button is pressed with the mouse cursor
on a component.
public void mouseClicked( MouseEvent event )
Called when a mouse button is pressed and released on a
component without moving the mouse cursor.
Called when a mouse button is released after being pressed.
This event is always preceded by a mousePressed event.
Called when the mouse cursor enters the bounds of a
component.
Called when the mouse cursor leaves the bounds of a
component.
public void mouseReleased( MouseEvent event )
public void mouseEntered( MouseEvent event )
public void mouseExited( MouseEvent event )
Methods of interface MouseMotionListener
public void mouseDragged( MouseEvent event )
Called when the mouse button is pressed with the mouse
cursor on a component and the mouse is moved. This event is
always preceded by a call to mousePressed.
public void mouseMoved( MouseEvent event )
Called when the mouse is moved with the mouse cursor on a
component.
MouseListener and MouseMotionListener interface methods.
1 // MouseTracker.java
2 // Demonstrating mouse events.
3
4 // Java core packages
MouseTracker.java
5 import java.awt.*;
6 import java.awt.event.*;
7
Lines 25-26
8 // Java extension packages
9 import javax.swing.*;
10
Line 35
11 public class MouseTracker extends JFrame
12
implements MouseListener, MouseMotionListener {
13
14
private JLabel statusBar;
15
16
// set up GUI and register mouse event handlers
17
public MouseTracker()
18
{
19
super( "Demonstrating Mouse Events" );
20
21
statusBar = new JLabel();
22
getContentPane().add( statusBar, BorderLayout.SOUTH );
23
24
// application listens to its own mouse events
Register JFrame to
25
addMouseListener( this );
receive mouse events
26
addMouseMotionListener( this );
27
28
setSize( 275, 100 );
29
setVisible( true );
30
}
31
32
// MouseListener event handlers
33
34
// handle event when mouse released immediately after press
Invoked when user presses
35
public void mouseClicked( MouseEvent event )
and releases mouse button
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
{
statusBar.setText( "Clicked at [" + event.getX() +
", " + event.getY() + "]" );
}
MouseTracker.java
// handle event when mouse pressed
public void mousePressed( MouseEvent event )
{
statusBar.setText( "Pressed at [" + event.getX() +
", " + event.getY() + "]" );
}
// handle event when mouse released after dragging
public void mouseReleased( MouseEvent event )
{
statusBar.setText( "Released at [" + event.getX() +
", " + event.getY() + "]" );
}
Invoked when user
Linebutton
42
presses mouse
Line 49
Invoked whenLine
user56
releases mouse
button after dragging mouse
Line 62
// handle event when mouse enters area
public void mouseEntered( MouseEvent event )
{
JOptionPane.showMessageDialog( null, "Mouse in window" );
}
// handle event when mouse exits area
public void mouseExited( MouseEvent event )
{
statusBar.setText( "Mouse outside window" );
}
Line 70
Invoked when mouse
cursor enters JFrame
Invoked when mouse
cursor exits JFrame
// MouseMotionListener event handlers
// handle event when user drags mouse with button pressed
public void mouseDragged( MouseEvent event )
Invoked when user
drags mouse cursor
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92 }
{
statusBar.setText( "Dragged at [" + event.getX() +
", " + event.getY() + "]" );
}
MouseTracker.java
// handle event when user moves mouse
public void mouseMoved( MouseEvent event )
{
statusBar.setText( "Moved at [" + event.getX() +
", " + event.getY() + "]" );
}
// execute application
public static void main( String args[] )
{
MouseTracker application = new MouseTracker();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
// end class MouseTracker
Invoked when user
77
moves mouseLine
cursor
MouseTracker.java
Adapter Classes
• Adapter class
–
–
–
–
Implements interface
Abstract
Provides default implementation of each interface method
Used when all methods in interface is not needed
Event adapter classes and the interfaces
they implement.
Event adapter class
ComponentAdapter
ContainerAdapter
FocusAdapter
KeyAdapter
MouseAdapter
MouseMotionAdapter
WindowAdapter
Implements interface
ComponentListener
ContainerListener
FocusListener
KeyListener
MouseListener
MouseMotionListener
WindowListener
Event adapter classes and the interfaces they implement.
1 // Painter.java
2 // Using class MouseMotionAdapter.
3
4 // Java core packages
5 import java.awt.*;
Painter.java
6 import java.awt.event.*;
7
Line 24
8 // Java extension packages
9 import javax.swing.*;
10
Lines 30-35
11 public class Painter extends JFrame {
12
private int xValue = -10, yValue = -10;
13
Lines 32-34
14
// set up GUI and register mouse event handler
15
public Painter()
16
{
17
super( "A simple paint program" );
18
19
// create a label and place it in SOUTH of BorderLayout
20
getContentPane().add(
21
new Label( "Drag the mouse to draw" ),
22
BorderLayout.SOUTH );
23
Register MouseMotionListener to
24
addMouseMotionListener(
listen for window’s mouse-motion events
25
26
// anonymous inner class
27
new MouseMotionAdapter() {
Override method mouseDragged,
28
but not method mouseMoved
29
// store drag coordinates and repaint
30
public void mouseDragged( MouseEvent event )
31
{
32
xValue = event.getX();
Store coordinates where mouse was
33
yValue = event.getY();
dragged, then repaint JFrame
34
repaint();
35
}
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
}
// end anonymous inner class
); // end call to addMouseMotionListener
Painter.java
setSize( 300, 150 );
setVisible( true );
Line 52
}
// draw oval in a 4-by-4 bounding box at the specified
// location on the window
public void paint( Graphics g )
{
// we purposely did not call super.paint( g ) here to
// prevent repainting
g.fillOval( xValue, yValue, 4, 4 );
}
Draw circle of diameter 4
where user dragged cursor
// execute application
public static void main( String args[] )
{
Painter application = new Painter();
application.addWindowListener(
// adapter to handle only windowClosing event
new WindowAdapter() {
public void windowClosing( WindowEvent event )
{
System.exit( 0 );
}
70
71
72
73
74
75 }
}
// end anonymous inner class
); // end call to addWindowListener
}
// end class Painter
Painter.java
Readings
• Ch 19
Download