Transcript 12Swingx

CompSci 230 S1 2016
Software Construction
AWT & SWING
Agenda

AWT






Swing – AWT’s successor




AWT Framework
Layout Managers
Painting
Basic Controls
Event Handling
GUI Component
Swing and threads
Graphics2D & Other Controls
Reading

Using Swing Components


Laying Out Components Within a Container


http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html
Writing Event Listeners

2
http://docs.oracle.com/javase/tutorial/uiswing/components/index.html
http://docs.oracle.com/javase/tutorial/uiswing/events/index.html
Lecture
2 12
Abstract Windowing Toolkit


Java’s AWT is a simple framework for developing graphical
user interfaces (GUIs)
Key AWT packages include:

java.awt

Contains core GUI component classes



Includes layout managers that layout composite components’ children
java.awt.event

Contains classes representing GUI events


Events represent things like window closing and restoration, button presses,
mouse movement, keystrokes, etc. Components generate events
Provides listener interfaces

3
Components are also known as widgets and may be “simple” (e.g. buttons,
textfields) or “composite” (e.g. windows, frames, panels)
Listener interfaces are provided that are intended to be implemented by
application developers; listener objects can be notified of events
Lecture
3 12
Generalisation
Component is an
abstract class.
A Component is something that
can be displayed on a GUI and
with which a user can interact.
A Container is a special component that can nest
other components, be they simple components
(e.g. Buttons, Labels) or themselves Containers
(e.g. Panels).
add( ) is a polymorphic method; it can take
as actual argument any kind of Component.
A Window is a special Container that can
be stacked, and moved to the front/back.
Nothing in this class hierarchy is application
specific. These classes provide a reusable resource
that
4 is extended to meet the needs of any
particular application.
A Frame is a special Window
with a title, menubar, and
border.
Specialisation
Lecture 12
AWT framework

Component




an abstract class
superclass of all GUI components except menu components and class
CheckboxGroup
repaint() schedules Component instance for repainting. The AWT framework
will subsequently call paint( ) on the Component
Container


the superclass for all components that contain other components
defines add(), for adding components to a container
Object
Component
Label
5
Button
Container
getSize( ) : int
setSize( width : int, height : int ) : void
setVisible( visible : boolean ) : void
repaint( g : Graphics ) : void
paint( g : Graphics ) : void
addMouseListener( listener : MouseListener ) : void
addKeyListener( listener : KeyListener ) : void
Many other
classes
setLayout( mgr : LayoutManager ) : void
add( c : Component ) : void
Lecture 12
Example:
Component
Label
Frame
Panel
TextField
*
Label
Button
Panel
Button
Panel
Container
Frame instance
add( c : Component ) : void
class Container extends Component {
private List<Component> children;
…
public void add( Component c ) {
children.add( c );
}
}
6
Panel
instance
Label
TextField
Label
instance 230 Software
instance
instance
COMPSCI
Design & Construction
Panel
instance
Button
instance
Panel
instance
Button
Lecture
instance
6 12
Example: Palindrome

Adding basic controls:
Panel inputPanel = new Panel( );
Panel outputPanel = new Panel( );
Panel buttonPanel = new Panel( );
Label prompt = new Label( "Word/phrase" );
TextField text = new TextField( 20 );
Label output = new Label( "Please enter a word/phrase" );
Button isPalindrome = new Button( "Is palindrome" );
Button quit = new Button( "quit" );
inputPanel.add( prompt );
inputPanel.add( text );
outputPanel.add( output );
buttonPanel.add( isPalindrome );
buttonPanel.add( quit );
add( inputPanel );
add( outputPanel );
add( buttonPanel );
7
Lecture 12
Layout Management

Aggregation
Component
*
<< interface >>
LayoutManager
Container
setLayout( mgr : LayoutManager ) : void
doLayout( )
add( c : Component ) : void
BorderLayout
8
1
layoutContainer( c : Container )
minimumLayoutSize( c : Container ) : Dimension
preferredLayoutSize( c : Container ) : Dimension
BoxLayout
GridLayout
FlowLayout
Lecture
8 12
Layout Managers

FlowLayout:


BorderLayout:



Simplest, just one row
This scheme defines five areas for the component.
All extra space is placed in the center area.
BoxLayout, GridLayout, …
setLayout(new BorderLayout());
add(new Button("North"), BorderLayout.NORTH);
add(new Button("South"), BorderLayout.SOUTH);
add(new Button("East"), BorderLayout.EAST);
add(new Button("West"), BorderLayout.WEST);
add(new Button("Center"), BorderLayout.CENTER);
9
Lecture 12
Component
Painting

Component implements a painting mechanism as follows:


repaint( ) schedules the component to be painted and should not
be overriden
paint( ) is intended to be implemented by subclasses to perform
subclass-specific painting

10
paint( g : Graphics )
repaint( )
E.g. A Button will paint itself as a button, a Panel will call paint on each child,
etc.
Lecture 12
Painting: System-triggered


A GUI component is displayed by "painting" it on screen.
System-triggered painting



When?

E.g. When the component is first shown/ covered and uncovered

This causes the component's paint() method to be called
You should place the component's rendering code inside a the paint method
When AWT invokes this method, the Graphics object parameter is pre-configured
with the appropriate state for drawing on this particular component
public void paint(Graphics g) {
Dimension size = getSize();
int d = Math.min(size.width, size.height);
int ed = d/20; // eye diameter
int x = (size.width - d)/2;
int y = (size.height - d)/2;
g.fillOval(x, y, d, d);
g.setColor(Color.black);
g.drawOval(x, y, d, d);
...
}
11
Application code
AWT Framework code
Framework detects that a window has moved
from the minimised to restored state. It calls
repaint( ) on the window component
Framework calls
paint( ) on the
Lecture 12
window component
Painting: Application-triggered
The program’s Java code determines that a component should be
repainted


E.g. when you change text, colors, …

It calls repaint(), which queues a paint request

Note:You never call paint() directly! You always call repaint()!
The event handler thread calls the component's paint() method

public void paint( Graphics g ) {
g.drawString( "(" + mouseX + ", " + mouseY + ")", mouseX, mouseY );
}
public void mousePressed( MouseEvent e ) {
mouseX = e.getX( );
mouseY = e.getY( );
Application code
repaint( );
}
AWT Framework code
Framework triggers an
event to which the
application responds
12
Framework calls
paint( ) on component
C
Application makes a repaint( )
request for a particular
component, C
Lecture 12
11
Painting: Palindrome Example

Traversing the nested structure:
class Container extends Component {
private List<Component> children;
…
public void add( Component c ) {
children.add( c );
}
public void paint( Graphics g ) {
for( Component c : children )
c.paint( );
}
1: paint( )
Frame instance
2: paint( )
Panel
instance
Label
instance
13
4: paint( )
TextField
instance
Panel
instance
Panel
instance
}
3: paint( )
7
5
9
6
Label
instance
8
Button
instance
Button
instance
Lecture
13 12
Event handling


Components generate events in response to user interaction
To hook in application-specific responses to events, listeners are
used

A listener is an object that is registered with a component; in handling
user interaction the component informs any registered listeners of
events
Registered listeners execute
Application code
event
Button instance
14
Listener instance
AWT Framework code
Framework detects a
button press and
generates an event
Framework waits for
next user interaction
Framework detects a
mouse drag and
generates an event
Lecture 12
Event handling
Interface for receiving ActionEvents
on a component
Interface for receiving key
stroke events on a component
Interface for receiving mouse
events (e.g. release, click,
enter and exit) on a component
<< interface >>
ActionListener
<< interface >>
KeyListener
<< interface >>
MouseListener
actionPerformed( e : ActionEvent ) : void
keyPressed( e : KeyEvent ) : void
keyReleased( e : KeyEvent ) : void
keyTyped( e : KeyEvent ) : void
mouseReleased( e : MouseEvent ) : void
mouseClicked( e : MouseEvent ) : void
mouseEntered( e : MouseEvent ) : void
mouseExited( e : MouseEvent ) : void
Button
AWT framework
addActionListener( listener : ActionListener )
1: addActionListener( appListener )
2: actionPerformed( )
Button instance
15
appListener :
ApplicationListener
ApplicationListener
Application
See API documentation for package java.awt.event for other
listener interfaces
Lecture 12
Event Handling

Event-driven programming is a programming style that uses a
signal-and-response approach to programming


The program itself no longer determines the order in which
things can happen




16
The sending of an event is called firing the event
Instead, the events determine the order
Typically, you do NOT call these event handlers yourself
Inversion of Control (IOC): Don't call us, we'll call you
Note: If you do want to capture events but forget to add a
listener, no events will be captured (a common omission).
Lecture 12
Events, Listeners, Adapters and
Handler Methods
Event
Listener / Adapter
Handler Methods
ActionEvent
ActionListener
actionPerformed
AdjustmentEvent
AdjustmentListener
adjustmentValueChanged
MouseEvent
MouseListener
MouseAdapter
mouseClicked
mouseEntered
mouseExited
mousePressed
mouseReleased
KeyEvent
KeyListener
KeyAdapter
keyPressed
keyReleased
keyTyped
ComponentEvent
ComponentListener
ComponentAdapter
componentShown
componentHidden
componentMoved
componentResized
17
Lecture 12
Example: SimpleButton.java
Put everything together

Controls + painting + Event handling (Note: old style!)

Steps:





Extends Frame Implements the ActionListener interface
Create a button
Add the button to the frame
Add an ActionListener to the button
Implement the actionPerformed method to handle the event
public class SimpleButton extends Frame implements ActionListener {
...
Button quit = new Button( "quit" );
add(quit);
quit.addActionListener( this );
...
public void actionPerformed( ActionEvent e ) {
System.exit( 0 );
}
Old Style!
}
Only ONE
event!
18
Lecture 12
Example: SimpleTextField.java
Handling more than one event

Use e.getSource() in the actionPerformed event handler to check which
button is pressed by the user.

Steps:





Extends Frame Implements the ActionListener interface
Create a button and two text fields
Add them to the frame (set border layout to Flow)
Old Style!
Add an ActionListener to the button and the TextField
Implement the actionPerformed method to handle two events
...
add(value);
add(quit);
value.addActionListener( this );
quit.addActionListener( this );
...
Note: the user must press 'enter' inside the
text field to activate the event.
public void actionPerformed( ActionEvent e ) {
if ( e.getSource( ) == quit ) { //
System.exit( 0 );
} else if (e.getSource() == value) {
copy.setText(value.getText());
getText/setText : Retrieves or sets the text
}
that is presented by this text component
}
19
Lecture 12
Example: PalindromeGUI.java
Anonymous Inner Classes
PalindromeGUI instance
No need to give inner classes names!

isPalindrome
quit
public class PalindromeGUI extends Frame {
private TextField text;
private Button isPalindrome, quit;
private Label output;
Button
instance
public PalindromeGUI( ) {
...
isPalindrome.addActionListener( new ActionListener( ) {
public void actionPerformed( ActionEvent e ) {
String enteredText = text.getText( );
...
have access to all instance
}
variables of the enclosing class
} );
quit.addActionListener( new ActionListener( ) {
public void actionPerformed( ActionEvent e ) {
System.exit( 0 );
}
Note: don’t need to use
} );
the getSource() method
...
listener
listener
Button
instance
actionPerformed( )
ActionListener
instance
ActionListener
instance
}
Old Style!
20
Lecture 12
Swing


Swing is a more complex and powerful successor to the AWT
Swing includes:

A richer set of GUI components, many of which are located in package
javax.swing






By convention, Swing component names are prefixed by J (e.g. JButton, JLabel etc.) and
are subclasses of JComponent, which is a subclass of the AWT’s Component class
Components that have separate models; the Swing framework originates
from the Model-View-Control (MVC) paradigm
Components that have a pluggable look-and-feel
Cosmetic improvements – e.g. buttons and labels can show images rather
than just text, and components can be decorated with a variety of borders
Swing’s painting model improves the AWT’s but is slightly more complex
Swing uses the AWT’s layout management and event handling
infrastructure
Data : Time value
Having separate data and state
models makes the Swing components
highly customizable, and enables
data sharing between components
21
Digital Clock
Analog Clock
import javax.swing.*;
Buttons on Digital Clock
Lecture 12
Knobs on Back of Analog Clock
Pluggable look and feel

Windows Look

Motif Look
( used on Linux)
22

Example: SwingDemo1.java
SwingDemo2.java, SwingDemo3.java
The Swing framework
allows, with minimal effort,
any Swing application to
take on the look-and-feel of
particular windowing
systems
A Swing GUI can also switch
to a different look-and-feel
at runtime
Note: Do not mix Swing and
AWT in the same window
Lecture 12
In principle, all GUI elements
are in the Component class
Swing Overview

Most Swing components are lightweight: formed by drawing in the underlying
window

Lightweight Components

Component
Container
Components that are software only
Object
JComponent
JScrollPane

JList
JPopupMenu
JPanel
Heavyweight Components

Components that have system-dependant peers (they integrate the Java components with the
local system’s native code)
Object
Component
Container
Window
23
Many other
classes
Dialog
Frame
JDialog
JFrame
Panel
Applet
JApplet
JWindow
Lecture 12
Top-Level Containers


Root
Top level of the "containment hierarchy"
Swing applications with GUI will have at least one top-level
container (contains all of the Swing components)

JApplet


JFrame



A class that enable applets to use Swing components
Frames are the simplest and most commonly used containers
A standard GUI based application will typically contain at least one frame
JDialog


A dialog box is just like a dialog box in Windows
Usually used to display warning messages, help the user or ask for information



JColorChooser
JFileChooser
JOptionPane

24
has many options for different types of dialog boxes
Richer components
JTabbedPane
JToolBar
JSplitPane
JSlider
JTable
25
JSpinner
JTree
Lecture 12
Example: HelloSwing.java
JFrame
JFrame – top level Container






Components should be added to the content pane rather than the frame
The java system creates a content pane automatically while initializing.The
content pane can be obtained with the function getContentPane()
The Default layout manager is BorderLayout and default look is Metal
Use setVisible(true) to display the frame on the screen
Use pack() to pack or setSize(…) to set the size
Causes this Window to be sized to fit the
preferred size and layouts of its subcomponents

JFrame closes automatically when you click on the close button. However,
closing the last JFrame does not result in the program exiting the Java
application

To exit the application


Use WindowListener to call System.exit(0), OR
Use EXIT_ON_CLOSE
import javax.swing.*;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
26
Lecture 12
Example: HelloWorldSwing.java
Swing and threads



Most Swing components are not thread-safe.
 Threads run at the same time. Problems arise if one thread
alters things in another thread, without them being
synchronised.
 Need to be careful!
Solution is to make sure all code that creates and modifies
Swing components executes in the same 'event-dispatching'
thread
Start a Swing application using the following code..
New Style!
27
public static void main (String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
Lecture 12
createAndShowGUI()


All the code to set up and start the GUI is placed in the static
method createAndShowGUI
Steps:


Construct a JFrame (a GUI window) with a title.
frame.setDefaultCloseOperation()




Quit the application when the frame is closed
Add components to the content pane
frame.pack()
frame.setVisible(true)
private static void createAndShowGUI() {
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
}
28
Lecture 12
Example: TempConvGUI.java
A Simple Swing App


Responding to user actions by using a JOptionPane
JOptionPane makes it easy to pop up a standard dialog box that
prompts users for a value or informs them of something:

showConfirmDialog:


showInputDialog:


Prompt for some input.
showMessageDialog :


Asks a confirming question, like yes/no/cancel.
Tell the user about something that has happened.
showOptionDialog:

The Grand Unification of the above three.
fahrString = JOptionPane.showInputDialog("Enter the temperature in F");
fahr = Double.parseDouble(fahrString);
cel = (fahr - 32) * 5.0/9.0;
JOptionPane.showMessageDialog(null,"The temperature in C is, " + cel);
29
Lecture 12
Example: SwingPaintDemo.java
The Paint Methods - Swing

Same rules to AWT’s component


except that Swing further factors the paint() call into three
separate methods, which are invoked in the following order:




paint() gets called when it's time to render
protected void paintComponent(Graphics g)
protected void paintBorder(Graphics g)
protected void paintChildren(Graphics g)
Swing programs should override paintComponent() instead of
overriding paint().
void paintComponent(Graphics g) {
Dimension size = getSize();
int x = 0;
int y = 0;
int i = 0;
while(x < size.width && y < size.height) {
g.setColor(i%2==0? Color.red : Color.white);
g.fillOval(x,y,size.width-(2*x),size.height-(2*y));
x+=10; y+=10; i++;
}
30
Lecture 12
Example: SwingMouseDemo.java
Painting & Mouse Events

Mouse Event : mousePressed
JPanel
class MousePositionJPanel extends JPanel {
private int mouseX, mouseY;
public MousePositionJPanel( ) {
mouseX = 100;
mouseY = 100;
addMouseListener( new MouseAdapter( ) {
public void mousePressed( MouseEvent e ) {
mouseX = e.getX( );
mouseY = e.getY( );
repaint( );
}
} );
}
public void paintComponent( Graphics g ) {
super.paintComponent( g );
g.drawString( "(" + mouseX + ", " + mouseY + ")", mouseX, mouseY );
}
}
31
Lecture 12
Component
paint( g : Graphics ) : void
repaint( ) : void
JComponent
<< interface >>
MouseListener
public void paint ( Graphics g ) {
paintComponent( g );
// Code to paint border.
}
public void paintComponent( Graphics g ) {
// Code to paint the background.
}
paintComponent( g : Graphics )
JPanel
MousePositionJPanel
public void paintComponent( Graphics g ) {
// Code to paint a panel’s background.
}
public void paintComponent( Graphics g ) {
// Make sure the background is painted.
super.paintComponent( g );
// Now do custom painting.
g.drawString ( "(" + mouseX + ", " + mouseY + ")",
mouseX, mouseY );
}
For custom painting in Swing, JComponent subclasses should override paintComponent( ) (and, in general,
make a super.paintComponent( ) call).
JComponent subclasses should not generally override paint( ) or repaint( ).
32
Lecture 12
Run-time call stack for painting a
MousePositionJPanel instance
JPanel.paintComponent( )
Graphics.drawString( )
MousePositionJPanel.paintComponent( )
MousePositionJPanel.paintComponent( )
MousePositionJPanel.paintComponent( )
JComponent.paint( )
JComponent.paint( )
JComponent.paint( )
JComponent.paint( )
(1)
(2)
(3)
(4)
MousePositionJPanel.paintComponent( )
(1)
(2)
(3)
(4)
(5)
(6)
33
JComponent.paint( )
JComponent.paint( )
(5)
(6)
The paint( ) message sent to a MousePositionJPanel object is bound to JComponent’s paint( )
method.
JComponent’s paint( ) method calls paintComponent( ), which is bound to class MouseMotionPanel’s
paintComponent( ) method.
MouseMotionPanel’s paintComponent( ) method calls it’s superclasses’ paintComponent( ) method
causing JPanel’s paintComponent( ) method to be executed.
Control returns to MousePositionJPanel’s paintComponent( ) method which then calls drawString(
) on a Graphics instance; class Graphics’ drawString method is executed.
Control returns to MousePositionJPanel’s paintComponent( ) method which then terminates
execution.
Control returns the JComponent’s paint( ) method which then also terminates, completing the
painting process.
Lecture 12
Graphics & Graphics2D

Old graphics context: java.awt.Graphics


New graphics context: java.awt.Graphics2D



Used in Java 1.0 and 1.1, now obsolete
Part of Java 2D (in Java 1.2 and later)
Although paintComponent() takes a Graphics object, what you get is
really a Graphics2D!
Basic methods for painting (Graphics and Graphics2D):





drawLine()
clearRect(), drawRect(), draw3DRect(), fillRect(), fill3DRect()
drawArc(), fillArc(), drawOval(), fillOval()
drawPolygon(), fillPolygon(), drawPolyLine()
drawString()
public void paintComponent(final Graphics g) {
Graphics2D g2d = (Graphics2D) g; // Just cast it…
// Use g2d
}
34
Lecture 12
Java 2D

Support for arbitrary shapes


A single draw() method, a single fill()
Draws or fills anything implementing





Pen styles implement the Stroke interface (BasicStroke)



Line2D, Rectangle2D, RoundRectangle2D
Arc2D, Ellipse2D
QuadCurve2D, CubicCurve2D
...
Different line widths, patterns, join styles
Use setStroke()
Fill patterns implement the Paint interface

Color: Solid fill, default color space sRGB (rgb + alpha)

Color.RED, Color.GREEN, Color.BLACK, ...
Color cyan2 = new Color(0, 255, 255); // Between 0 and 255



35
TexturePaint: Tiles a picture (repeats as necessary)
GradientPaint: A gradient between two colors
Use setPaint() or the older setColor()
Lecture 12
Example: MenuDemo.java
Basic Controls

JButton

With text and/or graphic labels

Create an ImageIcon
ImageIcon saveIcon = createImageIcon("save.gif");
JButton saveButton = new JButton("Save", saveIcon);
saveButton.setMnemonic(KeyEvent.VK_S);
Alt-S



protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = ToolBarDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL); ...
Mnemonics: keyboard accelerators that let you use Alt+someChar to trigger the button
Handling event

Use ActionListener
JMenu

saveButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
output.append("Save ");
}
Anonymous Inner class
});
A menu usually appears either in a menu bar or as a popup menu.

It can contain menus, menu items, radio button menu items, check box menu items, and separators.
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("A Menu");
menuBar.add(menu);
JMenuItem menuItem =
new JMenuItem("A Menu Item");
menu.add(menuItem);
36
Finds a resource (image
file) with a given name
menuItem.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
output.append("click a menu ");
}
});
frame.setJMenuBar(demo.createMenuBar());
Example: ComboBoxDemo.java
Basic Controls

JComboBox

A JComboBox, which lets the user choose one of several choices, can have two very different
forms :uneditable combo box (a button and a drop-down list of values) or editable
String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
petList = new JComboBox<String>(petStrings);

Event: ActionListener



Method: void actionPerformed(ActionEvent e)
Use getSelectedItem
String petName = petList.getSelectedItem().toString();
output.append(petName);
JList


A JList presents the user with a group of items to choose from.
Lists can have many items, so they are often put in scroll panes.
list = new Jlist<String>(petStrings);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);

Event: ListSelectionListener


37
Method: void valueChanged(ListSelectionEvent e)
Use getSelectedValue
list.addListSelectionListener( new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {
if (list.getSelectedIndex() == -1) { //No selection
output.append("No selection");
} else { //Selection
output.append(list.getSelectedValue().toString());
...
Example: BorderDemo.java
General-Purpose Containers

JPanel

A second-level container used to hold components within a top-level container such
as a frame or a dialog



Add other components inside using add() (can contain other JPanels)
The default layout is “BorderLayout”
Border


Create a Border object by calling BorderFactory
Use setBorder() to set the border
leftPanel.setBorder(BorderFactory.createTitledBorder("Left"));

JScrollPane


Provides a scrollable view of a component
Used to view a portion of a component that is too large to fit
JScrollPane s = new JScrollPane( component_to_be_scrolled );
38
TitledBorder
EtchedBorder
Example: SplitPaneDemo.java
General-Purpose Containers

JSplitPane

Displays two components, either side by side or above each other
JButton left = new JButton("Left Button" );
JButton right = new JButton("Right Button");
JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, right);
split.setOneTouchExpandable(true);
split.setDividerLocation(50);

JToolBar

Acts basically like a JPanel for buttons
JToolBar toolBar = new JToolBar();
39
Example: ColorChooserDemo.java
JDialog Boxes
JColorChooser



JColorChooser provides a pane of controls designed to allow a user to manipulate
and select a color.
To open:

JColorChooser.showDialog(…)


Arguments: parent component, title string, initially selected colour
Return value:
 Selected colour if “OK” is chosen
 Null if “cancel”
Anonymous Inner class
JButton button = new JButton("Colour");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Color newColor = JColorChooser.showDialog(panel, "Fill Color", Color.blue);
panel.setBackground(newColor);
}
Return the selected color
});
40
Lecture 12
Example: FileChooserDemo.java
JDialog Boxes

JFileChooser


JFileChooser provides a simple mechanism for the user to choose a file
Methods



showOpenDialog(Component parent)
showSaveDialog(Component parent)
showDialog(Component parent, String approveButtonText)


Pops up a custom file chooser dialog with a custom approve button
Returns:

The return state of the file chooser on popdown:



JFileChooser.CANCEL_OPTION
JFileChooser.APPROVE_OPTION (yes, ok)
JFileChooser.ERROR_OPTION if an error occurs or the dialog is dismissed
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(FileChooserDemo.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
System.out.println(file.getPath());
} else
System.out.println(“Cancel”);
41
Lecture 12
JDialog Boxes
JOptionPane



You can create and customize several different kinds of dialogs
Static Methods

showConfirmDialog


Asks a confirming question (yes/no/cancel)
Icons, messages and buttons: OK, OK/Cancel, Yes/No,Yes/No/Cancel
JOptionPane.showConfirmDialog(p, "Message", "Title", JOptionPane.YES_NO_OPTION);

showMessageDialog

Tells the user about something that has happened
Icons, messages and OK buttons

JOptionPane.showMessageDialog(p, "Message", "Title", JOptionPane.ERROR_MESSAGE);
Example: OptionPaneDemo.java
42
Lecture 12
Example: OptionPaneDemo.java
JDialog Boxes

JOptionPane

showInputDialog


Prompts for some input
Icons, messages, text fields, combo boxes and buttons
String inputValue;
inputValue = JOptionPane.showInputDialog("Enter first integer");
Object[] possibleValues = { "First", "Second", "Third" };
Object selectedValue = JOptionPane.showInputDialog(p, "Choose one",
"Input from Combo box",JOptionPane.INFORMATION_MESSAGE,
null, possibleValues, possibleValues[0]);
An array

showOptionDialog


Initial selected value
Unifies the above three
Icons, messages, arrays of buttons or other components
Object[] options = { "Good", "Normal", "Bad" };
JOptionPane.showOptionDialog(p, "Click OK to continue", "Warning",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,null,
options, options[0]);
43
An array
Initial value
Lecture 12
Review

Event source:


Event:


a user interaction (e.g. a click on the button)
Event listener:


44
a GUI component that generates / fires an event
an object that has implemented event handlers to react to an event
event listeners must be registered with an event source in order to
receive notification
Lecture 12