Transcript Swing

Graphical User Interface
Programming
GUI

Graphical User Interface


event driven programming
Java GUI programming


AWT (Abstract Window Toolkit)
Swing
Event driven programming

Uses a signal-and-response approach






Events and event handlers
Asynchronous
Event = object that act as a signal to another
object
Listener = event receiver
One event might have zero or more listeners.
Listeners can receive events from different
objects.
Event driven programming

One event might have zero or more listeners.
Listerner A
Button
X
Listerner B
Listerner C
Event driven programming

Listeners can receive events from different
objects.
Button
X
Listerner A
Button
Y
Button
Z
Listerner B
Typical events





User moves the mouse.
User clicks the mouse button.
User clicks the mouse button in a button in a
window.
User presses a key on the keyboard.
Timer event occurs.
Typical programming and event
driven programming

Up to now your programs consisted of lists of
statements executed in order.

In event-drive programming, you create
objects that can fire events, and you create
listener objects that react to the events.


You don’t know the order ahead of time.
Typically, your code never directly calls the
listener methods.
Windows
via Swing’s JFrame
Creating a window in Swing
import javax.swing.JFrame;
…
JFrame f = new JFrame( “My Simple Frame” );
f.setSize( 300, 200 ); //w, h
f.setDefaultCloseOperation(
JFrame.DO_NOTHING_ON_CLOSE );
…
f.setVisible( true );
Adding a button to a window
(JFrame)
import javax.swing.JButton;
…
//create the button
JButton b1 = new JButton( “Click to end program” );
//associate the listener with this button (next slide)
MyButtonListener listener = new MyButtonListener();
b1.addActionListener( listener );
f.add( b1 );
//add the button to our frame
Our button listener
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MyButtonListener implements ActionListener {
public void actionPerformed ( ActionEvent e ) {
System.exit( 0 );
}
}
(Typical) Steps
1.
2.
3.
4.
5.
6.
Create the frame.
Create the button.
Create the action listener for the button.
Add the action listener to the button (register
the action listener with the button).
Add the button to the frame.
Show the frame.
Pixel


Smallest unit of space on which your screen
can write.
Contraction for … what?
Useful JFrame methods



public JFrame ( )
public JFrame ( String title )
public void setDefaultCloseOperation ( int operation )






JFrame.DO_NOTHING_ON_CLOSE
JFrame.HIDE_ON_CLOSE
JFrame.DISPOSE_ON_CLOSE
JFrame.EXIT_ON_CLOSE
Note: The close-window-button is part of the JFrame (not
a JButton)
public void setSize ( int width, int height )
More useful JFrame methods






public void setTitle ( String title )
public void add ( Component componentAdded )
public void setLayout ( LayoutManager manager )
public void setJMenuBar ( JMenuBar menubar )
public void dispose ( )
public void setVisible ( boolean makeVisible )
Buttons
via Swing’s JButton
Buttons (JButton)


Different kinds of components require
different kinds of listener classes to handle the
events they fire.
A button fires events known as action events,
which are handled by listeners know as action
listeners.
Back to creating a window in Swing
import javax.swing.JFrame;
…
JFrame f = new JFrame( “My Simple Frame” );
f.setSize( 300, 200 ); //w, h
This is not a very
f.setDefaultCloseOperation( OO approach!
JFrame.DO_NOTHING_ON_CLOSE );
…
f.setVisible( true );
A more OO approach to creating a
window in Swing
import javax.swing.JFrame;
public MyFrame extends JFrame {
public static final int sWidth = 300;
public static final int sHeight = 200;
MyFrame ( ) {
super( “My More OO Simple Frame” );
setSize( sWidth, sHeight );
setDefaultCloseOperation(
JFrame.DO_NOTHING_ON_CLOSE );
…
setVisible( true );
}
…
}
JLabel – a line of text

Simply a line of text appearing in a window.
import javax.swing.JLabel;
…
JLabel label = new JLabel( “hello there.” );
add( label );
Programming in Color
import java.awt.Color;
…
Color.BLACK
 Also



Color.BLUE, Color.CYAN, Color.DARK_GRAY, …
Or you can specify/create your own colors by specifying
the argb or rgb values in the Color ctor.
Use getContentPane().setBackground( Color.BLUE );
to change the background color of your JFrame.
Programming in color

Colors are represented by their RGB value.





R=red
G=green
B=blue
When R is the largest value, the color has more red
than the other components. What happens when
r=g=b?
Sometimes ARGB is used where A=alpha
(opacity)
Layout Managers



Controlling the placement of
components in a container (our
frame)
So far, we simply add components to a container and accept
whatever default layout is presented.
Layout manager – describes how the components are arranged.
Java provides many layout managers.








Border (in book)
Box (not in book)
Card (not in book)
Flow (in book)
Grid (in book)
Grid bag (not in book)
Group (not in book)
Spring (not in book)
BorderLayout

Places the components in five areas:
1.
2.
3.
4.
5.

North
South
East
West
Center
You specify the area in the add method.

add( new JLabel(“me”), BorderLayout.NORTH );
Using the BorderLayout
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MyFrame extends JFrame {
public MyFrame ( ) {
super( “My frame w/ border layout.” );
setSize( 300, 200 );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setLayout( new BorderLayout() );
add( new JLabel( “first” ), BorderLayout.NORTH );
add( new JLabel( “second” ), BorderLayout.SOUTH );
…
setVisible( true );
}
}
FlowLayout

Simplest.

Arranges components one after another from
left to right and top to bottom in the order in
which one adds them.
Using the FlowLayout
import
import
import
import
java.awt.FlowLayout;
javax.swing.JButton;
javax.swing.JFrame;
javax.swing.JLabel;
public class MyFrame extends JFrame {
public MyFrame ( ) {
super( “My frame w/ flow layout.” );
setSize( 300, 200 );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setLayout( new FlowLayout() );
add( new JLabel( “first” ) );
add( new JButton( “second” ) );
…
setVisible( true );
}
}
GridLayout

Arranges components
on a 2D grid of given
size (i.e., rows and
cols specified via the
GridLayout ctor).

Each entry in the grid
will be stretched to
the same size.
GridLayout

Placement rules are more complicated.

Say we have a 2 x 3 (2 rows x 3 cols):

new GridLayout( 2, 3 )

If we subsequently add six things, they will appear
in a 2x3 grid of equally sized elements.

What happens if we add more or less?
GridLayout

Placement rules are
more complicated.

Say we have a 2 x 3 (2
rows x 3 cols).

Adding 7 or 8 items
causes a col to be added.

Adding fewer than 6
items causes a col(s) to
be deleted.
X
GridLayout

Placement rules are more complicated.

Say we have a 2 x 3 (2 rows x 3 cols).

To only honor the number of rows, specify a 0 for
the cols.

To honor only the number of cols, specify a 0 for
the rows.
Using the GridLayout
import
import
import
import
java.awt.GridLayout;
javax.swing.JButton;
javax.swing.JFrame;
javax.swing.JLabel;
public class MyFrame extends JFrame {
public MyFrame ( ) {
super( “My frame w/ flow layout.” );
setSize( 300, 200 );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setLayout( new GridLayout(0,1) ); //always a single col
add( new JLabel( “first” ) );
add( new JButton( “second” ) );
…
setVisible( true );
}
}
Summary of Layout Managers

FlowLayout


BorderLayout


Displays components from left to right in the order
in which they are added to the container.
Displays the components in five areas: N, S, E, W,
and Center. You specify the area in the add
method.
GridLayout

Lays out components in a grid with each
component stretched to fill its box in the grid.
Additional Layout Managers






Box (not in book)
Card (not in book)
Tabbed pane (not in book; not strictly a layout
manager)
Grid bag (not in book)
Group (not in book)
Spring (not in book)
BoxLayout
“either stacks its components on top of each other or
places them in a row - your choice” from
http://java.sun.com/docs/books/tutorial/uiswing/layou
t/box.html
CardLayout


Typically used to switch between different
panels.
Poor man’s version of tabbed pane.
choice here
causes change here
JTabbedPane


Not strictly a layout manager.
Typically preferred over CardLayout.
GridBagLayout
“… if you want to code by hand and do not want to use GroupLayout, then
GridBagLayout is recommended as the next most flexible and powerful
layout manager” from
http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html
GroupLayout
“… if you want to code by hand and do not want to use GroupLayout, then
GridBagLayout is recommended as the next most flexible and powerful
layout manager” from
http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html
Intended to be used by GUI builder.
SpringLayout

Intended to be used by GUI builder.
JPanel
a general purpose window-like
container
Panels (JPanel)



General purpose, window-like container
Groups objects
Components may be added to them (including
other panels)



hierarchical
Layout manager can be associated w/ a panel
Can be added to a JFrame
Example JPanels
JPanel w/ a top-to-bottom
BoxLayout
subclass of JPanel w/ a
left-to-right BoxLayout
subclass of JPanel w/ a
top-to-bottom BoxLayout
JPanel w/ a top-to-bottom
BoxLayout
JPanel Example
import
import
import
import
import
import
import
import
import
javax.swing.JFrame;
javax.swing.JPanel;
java.awt.BorderLayout;
java.awt.GridLayout;
java.awt.FlowLayout;
java.awt.Color;
javax.swing.JButton;
java.awt.event.ActionListener;
java.awt.event.ActionEvent;
public static void main ( String[] args ) {
PanelDemo gui = new PanelDemo( );
gui.setVisible( true );
}
public void actionPerformed ( ActionEvent e ) {
String buttonString = e.getActionCommand();
public class PanelDemo extends JFrame
implements ActionListener
{
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
private JPanel redPanel = new JPanel();
}
private JPanel whitePanel = new JPanel();
private JPanel bluePanel = new JPanel();
if (buttonString.equals("Red"))
redPanel.setBackground( Color.RED );
else if (buttonString.equals("White"))
whitePanel.setBackground(Color.WHITE);
else if (buttonString.equals("Blue"))
bluePanel.setBackground( Color.BLUE );
else
System.out.println( "Unexpected error.“ );
public PanelDemo ( ) {
super( "Panel Demonstration“ );
setSize( WIDTH, HEIGHT );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
JPanel buttonPanel = new JPanel( );
setLayout( new BorderLayout( ) );
buttonPanel.setBackground( Color.LIGHT_GRAY );
buttonPanel.setLayout( new FlowLayout( ) );
JPanel biggerPanel = new JPanel( );
JPanel Example
biggerPanel.setLayout( new GridLayout(1, 3) );
JButton redButton = new JButton( "Red“ );
redButton.setBackground( Color.RED );
redButton.addActionListener( this );
buttonPanel.add( redButton );
redPanel.setBackground( Color.LIGHT_GRAY );
biggerPanel.add( redPanel );
whitePanel.setBackground( Color.LIGHT_GRAY );
JButton whiteButton = new JButton( "White“ );
biggerPanel.add( whitePanel );
whiteButton.setBackground( Color.WHITE );
bluePanel.setBackground( Color.LIGHT_GRAY ); whiteButton.addActionListener( this );
buttonPanel.add( whiteButton );
biggerPanel.add( bluePanel );
JButton blueButton = new JButton( "Blue“ );
blueButton.setBackground( Color.BLUE );
blueButton.addActionListener( this );
buttonPanel.add( blueButton );
add( biggerPanel, BorderLayout.CENTER );
add( buttonPanel, BorderLayout.SOUTH );
}
}
JPanel Example

PanelDemo (JFrame w/ BorderLayout)

biggerPanel (w/ GridLayout of 1 row & 3 cols)





added at center
redPanel
whitePanel
bluePanel
buttonPanel (w/ FlowLayout)




added at south
redButton
whiteButton
blueButton
The Container class






Can have components added to it
JFrame & JPanel are descendents of Container
Container class = any descendent of Container
Component = any descendent of JComponent
You may add any component to any container
JComponent is derived from Container so you
may add a JComponent to a JComponent
The MVC Pattern
MVC = Model+View+Controller
Model-View-Controller (from
wikipedia.org)

Model

The domain-specific representation of the information on
which the application operates. Domain logic adds meaning
to raw data (e.g., calculating whether today is the user's
birthday, or the totals, taxes, and shipping charges for
shopping cart items).

Many applications use a persistent storage mechanism
(such as a database) to store data. MVC does not
specifically mention the data access layer because it is
understood to be underneath or encapsulated by the Model.
Model-View-Controller (from
wikipedia.org)

View

Renders the model into a form suitable for interaction,
typically a user interface element.

Multiple views can exist for a single model for different
purposes.
Model-View-Controller (from
wikipedia.org)

Controller

Processes and responds to events, typically user actions,
and may invoke changes on the model.
Basic MVC
Model
data1
data2
.
notify
manipulate
.
.
View
Controller
…
…
update()
…
…
Model-View-Controller (from
wikipedia.org)

Though MVC comes in different flavors, control flow generally works as
follows:
1.
2.
3.
4.
5.

The user interacts with the user interface in some way (e.g., presses a
button).
A controller handles the input event from the user interface, often via a
registered handler or callback.
The controller accesses the model, possibly updating it in a way appropriate
to the user's action (e.g., controller updates user's shopping cart).
A view uses the model (indirectly) to generate an appropriate user interface
(e.g., the view produces a screen listing the shopping cart contents). The
view gets its own data from the model. The model has no direct knowledge
of the view.
The user interface waits for further user interactions, which begins the cycle
anew.
By decoupling models and views, MVC helps to reduce the complexity in
architectural design, and to increase flexibility and reuse.
Model-View-Controller (from
wikipedia.org)
A simple diagram depicting
the relationship between the
Model, View, and Controller.
Note: the solid lines indicate
a direct association, and the
dashed lines indicate an
indirect association (e.g.,
observer pattern).
Observer pattern
“The observer pattern is a software design
pattern in which an object, called the subject,
maintains a list of its dependents, called
observers, and notifies them automatically of
any state changes, usually by calling one of
their methods. It is mainly used to implement
distributed event handling systems.”
from http://en.wikipedia.org/wiki/Observer_pattern
Model (data)
ConnectFour
|
|
V
MyConnectFour
View (output)
MyView
Main
Controller (input events)
MyController
A diagram depicting the relationship between the Model, View, and Controller
for the ConnectFour game. Note: the solid lines indicate a direct association,
and the dashed lines indicate an indirect association (e.g., observer pattern).
Note

Some designers combine/simply the M-V-C to
D-V where…



D is the document, data, or model,
V is the View, and
the controller is typically part of the view.
Menus and buttons
Menu bars, menus, and menu items

JMenuBar, JMenu, and JMenuItem

import:

javax.swing.JMenuBar


javax.swing.JMenu




ex. File
ex. Edit
ex. Help
javax.swing.JMenuItem



ex. the menu bar in an app
ex. Open in the File menu
ex. Cut in the Edit menu
implement ActionListener for events
Example
menu bar
menu
menu item
Example: creating a menu bar
…
public class MenuDemo extends JFrame implements ActionListener {
…
public MenuDemo ( ) {
…
JMenu colorMenu = new JMenu( “Add colors” );
JMenuItem greenChoice = new JMenuItem( “Green” );
greenChoice.addActionListener( this );
colorMenu.add( greenChoice );
…
JMenuBar bar = new JMenuBar();
bar.add( colorMenu );
setJMenuBar( bar );
}
…
}
Handling menu events




When we create a button or menu item, we
specify a string.
By default, that string becomes the action
command for that button.
The action command is provided to the
actionPerformed method.
The action command can be changed via
setActionCommand (there is also a
getActionCommand method as well).
Example: handle menu events
…
public class MenuDemo extends JFrame implements ActionListener {
…
public void actionPerformed ( ActionEvent e ) {
String action = e.getActionCommand();
if (action.equals( “Green” ))
greenPanel.setBackground( Color.GREEN );
else if (action.equals( “White” )
whitePanel.setBackground( Color.WHITE );
…
else
System.out.println( “Unexpected action” );
}
…
}
Advanced topic: sub/nested menus
submenu
submenus

Similarly to adding menu items to a menu, we
may also add menus to menus. (Note that
JMenuItem is a superclass of JMenu below.)
Text fields and text areas
Text field (JTextField)


A field that allows the user to enter a single line of
text.
Ex.
JTextField name = new JTextField( 30 );
…
String inputString = name.getText();
…
name.setText( “fred” );
JTextField f2 = new JTextField( “ethel”, 30 ); //default value

30 is the minimum number of visible characters (more may
be entered)
Text area (JTextArea)


Same as text field except it allows multiple lines.
Ex.
JTextArea theText = new JTextArea( 5, 20 );
JTextArea t2 = new JTextArea( “hello\nthere”, 5, 20 );
5 is the minimum number of visible lines.
20 is the minimum number of visible characters.
Some useful JTextComponent
methods

public String getText()

public boolean isEditable()

public void setBackground ( Color theColor )

public void setEditable ( boolean argument )

public void setText ( String text )