Download Programming Graphical User Interfaces

Document related concepts
no text concepts found
Transcript
Graphical User Interface Programming
Michael Brockway
November 14, 2016
Graphical User Interfaces
Users interact with modern application programs using graphical
components such as windows, buttons (plain, checkbox, radio buttons),
text boxes, menus, etc.
Early versions of Java used the abstract windowing toolkit (AWT) for
programming these.
These are little used now. Instead, we mostly use the Swing classes, aka
the Java Foundation Classes. These are little used now; instead we use
Swing aka Java Foundation Class components.
Swing ships with all recent versions of the Java standard edition toolkit,
and is the recommended library of classes for programming graphical user
interfaces.
This lecture contains a number of Java examples: the source files a
available for you to experiment with, in a companion zip archive.
Graphical Components
A graphical interface consists of graphical components, such as:
I
windows
I
buttons
I
menus
I
text fields
I
drop-down lists
A user interacts with the application by actions such as:
I
clicking on a button to choose a program option.
I
making a choice from a menu.
I
entering text in a text field.
I
dragging a scroll bar.
I
clicking on a window’s close button
Event-driven Programming
I
When you perform an action on a graphical component you generate
an event.
I
In event-driven programming the program has functions that
respond to events.
I
The program responds to events that the user generates in
interacting with GUI components.
I
The order of events is controlled by the user.
Java event-driven GUI Programming
I
In Java, you can get the GUI components you want merely by asking
for them.
I
Most of the work has already been done and is contained in the
Swing package.
I
Swing contains windows, frames, buttons, menus and other
components.
I
A user interacts with a GUI application by causing events.
I
The application must respond to events in the order they arrive.
I
Each time the user interacts with a component, an event is sent to
the application.
I
Different events are sent to different parts of the application.
I
The application has to work correctly no matter what the user does.
I
Usually an application ignores events that it is not programmed to
respond to.
Three Parts GUI Program
1. Graphical Components that make up the Graphical User Interface.
I
I
Swing objects.
You either use then as they are defined or extend them to your own
classes.
2. Listener methods that receive the events and respond to them.
I
I
I
You write these functions.
They are called by the event-handling mechanism.
Normally they in turn call application methods.
3. Application methods that do useful work
I
I
I
Receive data from GUI components.
Output data to GUI components for display.
Not themselves concerned with the user interface.
Container Classes
I
A GUI program consists of a collection of graphical components that
are all placed inside one or more windows.
I
You think of most components as being contained by a particular
window.
I
A container is an object that can hold other GUI components.
I
Visually, a container is an area of the screen and the objects it
contains are shown as smaller areas within it.
I
In Java terminology, a window is a container.
I
The buttons, sliders, icons and other GUI components are contained
(by the container).
The AWT Hierarchy
Object
...(many more classes)...
Component
Button
Canvas
Container
JComponent
JPanel (swing)
.... (many swing components)
Window
Frame
JFrame (swing)
Panel
Applet
JApplet (swing)
...(many other AWT Components)...
...(many classes)...
JFrame; JComponent and its subclasses
Class JFrame, derived from java.awt.Frame, is the usual main container
of a GUI.
The class JComponent, derived from awt.Container is one of the base
classes of swing. Here are some of its subclasses:
JComponent
AbstractButton
JButton
JLabel
JPanel
JSlider
JTextComponent
...(many more classes)...
Frames
In Java, a frame is an ‘outside’ window ...
I
that has nice borders, various buttons along the top border, and
other built-in things.
What you usually call a “window” Java calls a frame.
A frame is a container object: GUI components can be placed in it.
GUI-based application programs are usually organized around one or more
frames.
Elements of a Frame
Small GUI Example - TestFrame1.java
import java.awt.*;
import javax.swing.*;
public class TestFrame1 {
private JFrame frame;
public TestFrame1() {
makeFrame();
}
private void makeFrame() {
frame = new JFrame("Test Frame 1");
frame.setSize(200,100);
frame.setVisible( true );
}
}
Small GUI Example: Comments
I
The AWT is imported since it defines many classes that GUIs use.
I
I
I
I
The Swing package is imported since that is where JFrame is
defined.
I
I
I
Notice the ‘x’ in javax.swing.*.
A JFrame object is constructed.
I
I
Not strictly mecessary here but most GUI programs must do this.
Events are encapsulated by classes in the AWT package
java.awt.*
The reference variable frame refers to the JFrame object.
The object’s setSize() method sets its width and height in pixels.
The object’s setVisible() method makes it visible on the screen.
I
A call to setVisible(false) makes the frame invisible, but does not
destroy the software object
Another Example: Extending the Frame Class
I
I
A common way of writing a GUI is to define your own class by
extending the JFrame class
In the following example
I
I
I
The class MyFrame extends the class JFrame
MyFrame objects will be automatically re-painted when needed.
The standard parts of the frame – the background, the borders, the
controls – are drawn automatically by the Java system.
TestFrame2.java
public class TestFrame2 extends JFrame {
public TestFrame2() {
super("Test Frame 2");
makeFrame();
}
private void makeFrame() {
setSize(200,100);
setVisible( true );
}
}
Closing a Frame (Main Window)
I
By default, when the user closes a frame with the close button, the
frame is hidden.
I
The frame is then invisible, the frame still exists and the program
can make it visible again.
I
If you want different behaviour, then you need to either register a
window listener that handles window-closing events,
I
or you need to specify default close behaviour using the
setDefaultCloseOperation method: ...
public class TestFrame2 extends JFrame {
//... (constructor as before)
private void makeFrame() {
setSize(200,100);
setVisible( true );
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
setDefaultCloseOperation(...);
DO NOTHING ON CLOSE
I
Don’t do anything when the user requests that the window close.
I
Instead, the program should probably use a window listener that
performs some other action in its windowClosing method.
HIDE ON CLOSE (the default for JDialog and JFrame)
I
Hide the window when the user closes it.
I
This removes the window from the screen but leaves it displayable.
DISPOSE ON CLOSE (the default for JInternalFrame)
I
Hide and dispose of the window when the user closes it.
I
This removes the window from the screen and frees up any resources
used by it.
EXIT ON CLOSE (defined in the JFrame class)
I
Exit the application, using System.exit(0).
Two special Java methods
System.exit(int)
I
causes program to finish
I
a value 0 says no error
myWindow.dispose()
I
removes the window from the screen
Events and Event Handling
When a GUI program is running, the user generates an event by
interacting with a GUI component
For a program to respond to an event there must be an event listener for
it.
The event listener object contains listener methods for various types of
events
If there is no listener for an event, the event is ignored.
Event Objects
Events in Java are encapsulated in objects
I
A WindowEvent object represents an event sent by a window (resize,
close, ...);
I
An ActionEvent object represents an event sent by a button, text
field, or menu;
I
An ItemEvent object represents an event from a checkbox,
choicebox, or list (choice of an item);
I
A TextEvent represents an event from a text component
I
An AdjustmentEvent represents an event from a scrollbar
I
A KeyEvent represents an event from a key (press, release)
I
A MouseEvent or MouseMotionEvent represents events a mouse
(click, press, release, drag, ...).
Event Listener Objects
When an event is sent by the GUI component, a method in the listener is
to be invoked.
An event listener is an object in the program. In particular, for each
event the program must respond to, the program must
I
create an event listener object for the type of event.
I
register the listener object with the GUI component that
generates the event (or with a component that contains it.)
ButtonDemo1.java: A program with a button
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonDemo1 extends JFrame {
private JButton bChange;
public ButtonDemo1() { // constructor
super("Button Demo");
makeFrame();
}
private void makeFrame() {
bChange = new JButton("Click Me!"); // construct a Button
add( bChange );
// add it to frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200, 150);
setVisible(true);
}
}
Comments
I
I
To construct a JButton object, use new.
Then add the button to the frame’s content pane.
I
I
I
I
The JButton now will be displayed when the frame is displayed, and
respond visually when the user clicks on it.
Clicking on the button generates events, but so far, there is no event
handling.
Also the button fills the whole content pane.
I
We shall deal with this first, then return to the event handling.
Layout Managers
I
When you add() buttons (and other components) to a content pane,
a layout manager automatically decides what size they will be and
where they will go.
I
I
I
convenient, because you can add components without worrying
about the details.
You say what components you want and the layout manager lays
them out in the picture.
The layout manager sometimes makes odd choices.
I
There are several kinds of layout managers; each one has a different
style of positioning components.
I
They are all classes in java.awt.
Layout Managers
I
FlowLayout
I
I
I
I
I
GridLayout
I
I
I
I
Components are set to a reasonable preferred size
then positioned within container in the order they are added
starting from top left, working from left to right;
When available width is used, next row is started.
Number of rows and number of columns is specified;
Components are set to a reasonable preferred size
then positioned down the first column, then down the second
column, etc.
BorderLayout
I
I
Components are assigned to North, South, East, West and Center
regions of the container;
they are sized to fill the whole of their region.
Setting the Layout Manager
The problem with the example is that the content pane of a JFrame has
a BorderLayout by default
I
The button expands to fill the whole content pane due to
BorderLayout policy.
We fix this by using setLayout(new FlowLayout()) to override the
default. (See also ButtonDemo2.java in the example sources archive.)
.....
private void makeFrame() {
setLayout(new FlowLayout());
//set the layout
bChange = new JButton("Click Me!"); // construct a Button
add( bChange );
// add it to frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200, 150);
setVisible(true);
}
Result with Flow Layout Manager
Only one item has been added to the flow layout: it is centred in the first
(top) ‘row’ of the flow layout.
Action Listener
Back to the job of handling the event of a click on the button.
I
We need an ActionListener object.
I
This is a class which implements the
java.awt.event.ActionListener interface.
I
Interface ActionListener declares the single method:
public void actionPerformed( ActionEvent evt) ;
I
The ActionEvent parameter it expects is a
java.awt.event.ActionEvent object that represents an event (a
button click).
I
It contains information that can be used in responding to the event.
I
Since ActionListener is an interface, you use it with a class that will
implement the actionPerformed() method.
I
It is common to implement the interface in the same class that
contains the button(s):
Button Example with Action Listener (1 of 2)
ButtonDemo2.java
import java.awt.*;
import java.awt.event.*; //need this for ActionListener
import javax.swing.*;
public class ButtonDemo2 extends JFrame
implements ActionListener {
private JButton bChange;
public ButtonDemo2() { // constructor
super("Button Demo");
makeFrame();
}
Button Example with Action Listener (2 of 2)
private void makeFrame() {
setLayout(new FlowLayout());
// set the flow layout
bChange = new JButton("Click Me!"); // construct a Button
add( bChange );
// add it to frame
bChange.addActionListener(this);
// Register listener
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200, 150);
setVisible(true);
}
// Method to handle the button click
//
(required by ’implments’ contract)
public void actionPerformed(ActionEvent evt) {
getContentPane().setBackground(Color.blue);
}
}
Result with ActionEvent Handling
Before:
After:
Summary so far
General form of actionPerformed:
public void actionPerformed(ActionEvent evt) {
//look at data in ActionEvent: this may be useful
//send reults to GUI components (invoke methods on them)
}
General structure for GUI code:
I
I
Declare widget
Define attributes of widget
I
Text, Colour, Editable?, Size, ...
I
Add to container
I
Register an action listener
Click on an ActionEvent source (eg button) creates an ActionEvent
object which is sent to the actionPerformed() methods of all
ActionListeners registered with it.
A Further Example
Develop a new program:
I
A frame will hold two buttons, one labelled ”Red”, the other
”Green”.
I
Use a FlowLayout layout manager so the buttons will be nicely
positioned in the frame.
I
When the button marked ”Red” is clicked, the background will turn
red.
I
When the button marked ”Green” is clicked, the background will
turn green.
I
There will be an event listener that listens to the clicks from both
buttons.
I
When the ”close button” of the frame is clicked, the application will
quit.
Questions to consider
How many frames are there?
What GUI components will it/they contain?
What objects generate events?
What objects receive events?
Questions to consider
Just one frame, contining the ”Red” button and the ”Green” button.
Both buttons send ActionEvents. The frame sends a WindowEvent
(handled by default close operation).
TwoButtons.java (1 of 3)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoButtons extends JFrame
implements ActionListener {
private JButton redButton, grnButton;
public TwoButtons() {
super ("Two Buttons");
makeFrame();
}
Two Buttons: (2 of 3)
private void makeFrame() {
redButton = new JButton("Red");
grnButton = new JButton("Green");
setLayout(new FlowLayout());
add(redButton);
add(grnButton);
redButton.addActionListener(this);
grnButton.addActionListener(this);
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
setSize( 200, 150 );
setVisible(true);
}
Two Buttons: (3 of 3)
public void actionPerformed( ActionEvent evt) {
// check which command has been sent
if (evt.getActionCommand().equals("Red"))
getContentPane().setBackground(Color.red);
else
if (evt.getActionCommand().equals("Green" ))
getContentPane().setBackground(Color.green);
}
Method getActionCommand() returns a string. In case of a button this
is by default the label on the button.
An Alternative actionPerformed Method
ActionEvents have a method getSource() which returns an Object:
the GUI component which sent the event.
I
The actionPerformed method can use getSource() to decide which
button was clicked.
public void actionPerformed( ActionEvent evt) {
// check which button sent the event
if (evt.getSource() == redButton)
getContentPane().setBackground(Color.red);
else
if (evt.getSource() == grnButton)
getContentPane().setBackground(Color.green);
}
Output
Swing components JTextField and JLabel
I
A JTextField is a box that contains text.
I
The user can type text into the box and the program can get it and
then use it as data.
I
The program can write the results of a calculation to a JTextField
Constructors
I
I
I
I
I
I
I
JTextField()
JTextField(String text)
JTextField(int columns)
JTextField(String text, int columns)
A JTextField is used for input: when ENTER is typed, it issues an
ActionEvent.
A JLabel object simply displays text
I
I
Constructor JLabel(String text)
Useful for labelling other components: sych as JTextFields!
JTextField and JLabel Example (1 of 3)
CharCounter.java
I
User types text into upper text field and types ENTER
I
Character count is then calculated and displayed in lower text field.
JTextField and JLabel Example (2 of 3)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CharCounter extends JFrame
implements ActionListener {
private JLabel inLabel = new JLabel("Enter text:");
private JTextField inText = new JTextField(15);
private JLabel outLabel = new JLabel("Character count:");
private JTextField outText = new JTextField(8);
JTextField and JLabel Example (3 of 3)
public CharCounter() { //constructor
super("Character Counter");
setLayout(new FlowLayout());
add(inLabel); add(inText);
add(outLabel); add(outText) ;
inText.addActionListener(this);
outText.setEditable(false);
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
setSize(300, 120);
setVisible(true);
}
public void actionPerformed(ActionEvent evt) {
String stg = inText.getText();
outText.setText(""+stg.length());
}
}
setEditable()
Notice outText.setEditable(false); above.
Use this JTextField method to prevent the user from entering text into
the text field:
I
The setEditable() method has one boolean parameter:
I
I
true ⇒ field can be edited by user
false ⇒ field cannot be edited by user
In summary, common JTextField methods are
I
String getText()
I
void setText(String s)
I
setEditable(boolean b)
I
boolean isEditable()
I
void setBackground(Color c)
I
void addActionLister(ActionListener l)
JTextArea
I
Similar to text field, but allows multiple lines
I
Does not generate ActionEvent on ENTER, so not suitable for input
Constructors
I
I
I
I
I
I
JTextArea()
JTextArea(String text)
JTextArea(int rows, int columns)
JTextArea(String text, int rows, int columns)
Common methods
I
I
I
I
I
I
I
I
String getText()
void setText(String s)
append(String s)
setEditable(boolean b)
boolean isEditable()
void setBackground(Color c)
void setLineWrap(boolean b) - enable/disable wrapping
void setWrapStyleWord(boolean b) - wrapping on complete
words only
JTextArea
Default behavior is to expand width-wise as text fills the area.
setLineWrap(true) to make it wrap text to the following line.
setWrapStyleWord(true) to make it wrapping on whole words.
With these settings the text area does not expand with-wise but does
expand length-wise when it fills.
You can also give the text area scroll-bars by adding it to the container
inside a JScrollPane
I
a research exercise for you!
JTextArea Example (1 of 3): TextAppender.java
I
User types text into upper text field and types ENTER
I
The text is appended to the text in the lower text area.
I
The text in the text area wraps on whole words.
JTextArea Example (2 of 3)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextAppender extends JFrame
implements ActionListener {
private JLabel inLabel = new JLabel("Enter text:");
private JTextField inText = new JTextField(15);
private JLabel outLabel = new JLabel("Accumulated text:");
private JTextArea outText = new JTextArea(10, 15);
public TextAppender() { //constructor
super("Text Appender");
setLayout(new FlowLayout());
add(inLabel); add(inText);
add(outLabel); add(outText) ;
inText.addActionListener(this);
....
JTextArea Example (3 of 3)
outText.setEditable(false);
outText.setLineWrap(true);
outText.setWrapStyleWord(true);
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setVisible(true);
}
public void actionPerformed(ActionEvent evt) {
String stg = inText.getText();
inText.setText("");
if (outText.getText().length() == 0)
outText.setText(stg);
else
outText.append("; "+stg);
}
}
Design of an Application
Design and implement a GUI application that converts a temperature
expressed in Fahrenheit into Celsius.
I
There are three parts to the design:
1. The Graphical User Interface.
2. Listener methods.
3. Application methods.
I
First look at the application methods. The formula for converting
Fahrenheit into Celsius is this:
C = (F − 32) ∗ 5/9
Program Architecture
We shall have two classes:
1. a temperature class
2. a GUI class
The temperature class FTemperature.java models the data:
public class FTemperature {
private double fTemp;
public FTemperature() {} //constructors
public FTemperature(double ft) { fTemp = ft; }
public void setFTemp(double ft) { fTemp = ft; }
public double getFTemp()
{ return fTemp; }
public double convFToC() {
return ((fTemp-32.0) * 5.0) / 9.0;
}
}
The GUI: 1 of 3
FToCGUI.java: preliminary version
The user enters text (a String) into the Fahrenheit text field. The string
will be converted into double format.
The GUI consists of JLabels and JTextFields placed into a JFrame
The GUI: 2 of 3
import
import
import
import
java.awt.*;
java.awt.event.*;
javax.swing.* ;
java.text.*;
public class FToCGUI extends JFrame
implements ActionListener {
private JLabel title = new JLabel("Convert temp F to C");
private JLabel inLabel = new JLabel("Fahrenheit");
private JLabel outLabel = new JLabel("Celsius");
private JTextField inFahr = new JTextField(7);
private JTextField outCel = new JTextField(7);
...
The GUI: 3 of 3
public FToCGUI() { //constructor
super("F To C");
setLayout( new FlowLayout() );
add(title); add(inLabel); add(outLabel);
add(inFahr); add(outCel);
inFahr.addActionListener(this);
outCel.setEditable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(180, 150);
setVisible(true);
}
public void actionPerformed( ActionEvent evt) {
String userInput = inFahr.getText() ;
double ft = Double.parseDouble(userInput);
FTemperature temp = new FTemperature(ft);
outCel.setText(String.format("%5.2f", temp.convFToC()));
}
}
Notes
I
I
The FTemperature class knows nothing about the programs input,
output.
The FToCGUI needs to know about the FTemperature class:
I
I
I
its actionPerformed method constructs an instance and sends
messages to it.
NB the String.format() function: uses C-style formatting to make a
display string with 5 digits and 2-place rounding.
There is a problem with the prelminary version of FToCGUI: when
the user resizes the window, the layout goes awry, the labels
becoming separated from their text boxes.
I
We need panels to fix this.
Panels, JPanel and Layout
A panel is a container for components that does not create a window of
its own. A ‘logical’ rectangle on the screen.
I
to help organise layout
I
add components to a panel
I
nested them: add components, panels to ‘bigger’ panels or frame
I
a panel is both a component and a container.
JPanel is the swing version of a panel.
I
Components added to a panel become inseparable.
I
A panel corresponds to a rectangular section of the screen.
I
Each panel has its own layout manager that lays out the
components inside the panel.
I
The default layout manager of JPanel is flow
I
The content pane’s layout manager arranges the panels as if each
one were a single component.
I
Panels do not have visible edges.
JPanel Example: FToCGUI.java
Here is another version of the FToCGUI constructor:
public FToCGUI() { //constructor
super("F To C");
JPanel p1 = new JPanel(); p1.setLayout(new GridLayout(2,1));
JPanel p2 = new JPanel(); p2.setLayout(new GridLayout(2,1));
p1.add(inLabel); p2.add(outLabel);
p1.add(inFahr); p2.add(outCel);
JPanel p3 = new JPanel(); //default layout = flow
p3.add(p1); p3.add(p2);
setLayout(new GridLayout(2,1));
add(title); add(p3);
inFahr.addActionListener(this);
outCel.setEditable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(180, 150);
setVisible(true);
}
JPanel Comments
I
The panel p1 uses a grid layout to hold the input box underneath its
label;
I
The panel p2 uses a grid layout to hold the output box underneath
its label;
These two compound components are added to panel p3
I
I
I
I
side by side, since default layout is flow;
The title and p3 are added to the frame using grid layout.
The point of all this is that the layout is more robust against resizing
by the user.
I
Compare the resizing behaviour of this with the earlier version.
“Radio Buttons” - JRadioButton
I
Radio buttons generate action events just as do push buttons.
I
Use addActionListener(ActionEvent).
I
Use setActionCommand(String) if you want your code to use
getActionCommand() to recognise a paticular JRadioButton.
Normally radio buttons are placed in groups in two ways:
I
I
I
I
in a JPanel, to control how they are displayed, and also
in a javax.swing.ButtonGroup, to control which buttons may be
active simultaneously.
Clicking a radio button deselects all other buttons in the group
I
A button group is an object which must be constructed.
I
Radio buttons are then added to it.
I
Use boolean rBtn.isSelected() to tell whether JRadioButton
rBtn is selected.
JRadioButton Example: RadioButtons.java
I
A simple calculator adds, substract, multiplies integers;
I
I
I
I
Input is via two JTextFields; output is to a non-editable JTextField.
You choose operation using three JRadioButtons in a ButtonGroup.
Displays answer in decimal or hex: choose using two JRadioButtons
in a ButtonGroup.
See RadioButtons.java in example sources bundle.
JRadioButton Example ctd
I
Look at constructor:
I
I
I
I
I
I
Operation choice radio buttons are added to a JPanel for display at
top;
Display format choice radio buttons are added to a JPanel for display
at bottom;
The text boxes are each put in a JPanel with their label;
The five JPanels are put in the frame (using another JPanel!)
All JTextFields and JRadioButtons assigned an ActionListener.
Look at the actionPerformed method:
I
I
I
ENTER in a text box, click on a radio button all trigger the same
action (otherwise we could use getActionCommand() or getSource()
to decide what to do);
isSelected() is used to see which operation is chosen;
isSelected() is used to see which output format is active;
Border Layout: BorderLayoutEx.java
I
I
Default for JFrame’s ContentPane;
Organises window into 5 regions:
I
I
I
BorderLayout.NORTH, BorderLayout.SOUTH,
BorderLayout.EAST, BorderLayout.WEST, BorderLayout.CENTER
Each region holds only one item, but it can be a JPanel or other
container holding several components.
Border Layout in RadioButtons.java
I
The simple calculator example uses BorderLayout: look again at its
constructor.
I
I
I
I
EAST, WEST not used; they shrink to a ‘small’ (zero!) size.
The operation choice radio button panel is NORTH.
The output format choice radio button panel is SOUTH.
The three text boxe panels are in an outer JPanel in the CENTER.
Mouse Event Handling
I
Java provides two event listener interfaces for dealing with mouse
events
I
I
I
MouseListener methods
I
I
I
I
I
mouseEntered(MouseEvent evt); mouseExited(MouseEvent evt)
mousePressed(MouseEvent evt)
mouseReleased(MouseEvent evt)
mouseClicked(MouseEvent evt)
MouseMotionListener methods
I
I
java.awt.event.MouseListener listens for MouseEvents generated
when the mouse has a button pressed, released, or clicked, or when it
enters or exits the bounds of the component.
java.awt.event.MouseMotionListener listens for MouseEvents
generated when the mouse is dragged or moved across the
component. (Dragged = moved with a button down)
mouseMoved(MouseEvent evt); mouseDragged(MouseEvent evt)
java.awt.event.MouseEvent has methods to report mouse
coordinates and button state: refer to API documentation.
Example - MouseTracker.java
A simple example: implements all mouse methods and report mouse
position and button status on console:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseTracker extends JFrame
implements MouseListener, MouseMotionListener {
public MouseTracker () {
super("Demonstration of Mouse Events");
addMouseListener (this);
addMouseMotionListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 300);
setVisible(true);
}
....
Example - continued
//helper
public void sMsg(String legend, MouseEvent evt) {
System.out.printf("%s at [%d, %d]; button state = %d\n",
legend, evt.getX(), evt.getY(), evt.getButton());
}
//MouseListener methods ...
public void mouseClicked(MouseEvent e)
public void mousePressed(MouseEvent e)
public void mouseReleased(MouseEvent e)
public void mouseEntered(MouseEvent e)
public void mouseExited (MouseEvent e)
{sMsg("Clicked", e);}
{sMsg("Pressed", e);}
{sMsg("Released",e);}
{sMsg("Entered", e);}
{sMsg("Exited", e);}
//MouseMotionListener methods
public void mouseDragged (MouseEvent e) {sMsg("Dragged", e);}
public void mouseMoved (MouseEvent e)
{sMsg("Moved", e);}
}
Another Example; with low-level Graphics
A slightly more amusing example is ClickMe.java
ClickMe Example ctd
I
A simple reaction-timing game
I
The game window is a single JPanel, in CENTER, plus a status
display, SOUTH
I
A string “Click me” is displayed in a random position on the game
window and the time elapsed until a mouse click lands near it is
displayed in the status display.
I
A JPanel can be ‘painted on’ using the low-level graphics methods
of the java.awt.Graphics object associated with the JPanel.
Provide a method PaintComponent(Graphics g) in the game
class, which extends the JPanel.
I
I
I
It starts with super.paintComponent(g) to paint the underlying
JPanel, then does game-specific painting.
Do not usually call super.paintComponent() directly; rather, call
JPanel’s repaint() method to ‘queue’ a repaint of the window.
PaintComponent(Graphics)
In ClickMe.java ...
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (newPos) {
//If target moved,
g.setColor(getBackground());
// erase it
g.drawString("Click me!", x, y);
x = rng.nextInt(getWidth()-60);
// new random
y = 20+rng.nextInt(getHeight()-25); // coordinates
refTime = System.currentTimeMillis();
newPos = false;
}
if (x >=0 && y >=0) {
//except for initial paint,
g.setColor(Color.red);
// show tgt at current
g.drawString("Click me!", x, y); // position
}
}
Dialogues
I
Displayed to give information or solicit input
I
I
Modal dialogues block all other interaction until dismissed
Non-modal dialogues allow other interaction;
I
javax.swing.JOptionPane provides some ‘standard’ dialogues
I
I
I
I
may be undesirable
Message dialogue: message text plus an OK button.
Confirm dialogue has yes/no/cancel options
Input dialogue has a prompt and an input field; OK/cancel buttons
Message Dialogue: Dialogues.java
.....
JOptionPane.showMessageDialog(frame,
"The message", "Title",
JOptionPane.INFORMATION_MESSAGE);
.....
I
The last parameter chooses the information icon.
Confirm Dialogue: Dialogues.java
.....
int cnf = JOptionPane.showConfirmDialog(frame, "Question?");
System.out.printf("The result was %d\n", cnf);
.....
I
YES → 0, NO → 1, CANCEL → 2
Input Dialogue: Dialogues.java
.....
String inp = JOptionPane.showInputDialog(frame,
"Input your data", "Input Dialogue",
JOptionPane.QUESTION_MESSAGE);
System.out.printf("The input was ’%s’\n", inp);
.....
I
The last parameter chooses the question icon.
I
The return value on OK is the input string; CANCEL → null