74
Graphical User Graphical User Interface Interface Programming Programming

Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Embed Size (px)

Citation preview

Page 1: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Graphical User Interface Graphical User Interface ProgrammingProgramming

Page 2: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

GUIGUI

Graphical User InterfaceGraphical User Interface event driven programmingevent driven programming

Java GUI programmingJava GUI programming AWT (Abstract Window Toolkit)AWT (Abstract Window Toolkit) SwingSwing

Page 3: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Event driven programmingEvent driven programming

Uses a signal-and-response approachUses a signal-and-response approach Events and event handlersEvents and event handlers AsynchronousAsynchronous

Event = object that act as a signal to another Event = object that act as a signal to another objectobject

Listener = event receiverListener = event receiver One event might have zero or more listeners.One event might have zero or more listeners. Listeners can receive events from different Listeners can receive events from different

objects.objects.

Page 4: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Event driven programmingEvent driven programming

One event might have zero or more listeners.One event might have zero or more listeners.

Button X

Listerner A

Listerner B

Listerner C

Page 5: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Event driven programmingEvent driven programming

Listeners can receive events from different Listeners can receive events from different objects.objects.

Button Y

Button Z

Button X

Listerner A

Listerner B

Page 6: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Typical eventsTypical events

User moves the mouse.User moves the mouse. User clicks the mouse button.User clicks the mouse button. User clicks the mouse button in a button in a User clicks the mouse button in a button in a

window.window. User presses a key on the keyboard.User presses a key on the keyboard. Timer event occurs.Timer event occurs.

Page 7: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Typical programming and event Typical programming and event driven programmingdriven programming

Up to now your programs consisted of lists of Up to now your programs consisted of lists of statements executed in order.statements executed in order.

In event-driven programming, you create In event-driven programming, you create objects that can fire events, and you create objects that can fire events, and you create listener objects that react to the events.listener objects that react to the events. You don’t know the order ahead of time.You don’t know the order ahead of time. Typically, your code Typically, your code nevernever directly calls the directly calls the

listener methods.listener methods.

Page 8: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

WindowsWindows

via Swing’s JFramevia Swing’s JFrame

Page 9: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Creating a window in SwingCreating a window in Swing

import javax.swing.JFrame;import javax.swing.JFrame;

……JFrame f = new JFrame( “My Simple Frame” );JFrame f = new JFrame( “My Simple Frame” );f.setSize( 300, 200 ); //w, hf.setSize( 300, 200 ); //w, hf.setDefaultCloseOperation(f.setDefaultCloseOperation(

JFrame.DO_NOTHING_ON_CLOSE );JFrame.DO_NOTHING_ON_CLOSE );……f.setVisible( true );f.setVisible( true );

Page 10: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Adding a button to a window Adding a button to a window (JFrame)(JFrame)

import javax.swing.JButton;import javax.swing.JButton;

……

//create the button//create the button

JButton b1 = new JButton( “Click to end program” );JButton b1 = new JButton( “Click to end program” );

//associate the listener with this button (next slide)//associate the listener with this button (next slide)

MyButtonListener listener = new MyButtonListener();MyButtonListener listener = new MyButtonListener();

b1.addActionListener( listener );b1.addActionListener( listener );

f.add( b1 );f.add( b1 ); //add the button to our frame//add the button to our frame

Page 11: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Our button listenerOur button listener

import java.awt.event.ActionListener;import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;import java.awt.event.ActionEvent;

public class MyButtonListener implements ActionListener {public class MyButtonListener implements ActionListener {

public void actionPerformed ( ActionEvent e ) {public void actionPerformed ( ActionEvent e ) {

System.exit( 0 );System.exit( 0 );

}}

}}

Page 12: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

(Typical) Steps(Typical) Steps

1.1. Create the frame.Create the frame.

2.2. Create the button.Create the button.

3.3. Create the action listener for the button.Create the action listener for the button.

4.4. Add the action listener to the button (register Add the action listener to the button (register the action listener with the button).the action listener with the button).

5.5. Add the button to the frame.Add the button to the frame.

6.6. Show the frame.Show the frame.

Page 13: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

PixelPixel

Smallest unit of space on which your screen Smallest unit of space on which your screen can write.can write.

PixelPixel is a contraction for … what? is a contraction for … what?

Page 14: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Useful JFrame methodsUseful JFrame methods

public JFrame ( )public JFrame ( ) public JFrame ( String title )public JFrame ( String title ) public void setDefaultCloseOperation ( int public void setDefaultCloseOperation ( int

operation )operation ) JFrame.DO_NOTHING_ON_CLOSEJFrame.DO_NOTHING_ON_CLOSE JFrame.HIDE_ON_CLOSEJFrame.HIDE_ON_CLOSE JFrame.DISPOSE_ON_CLOSEJFrame.DISPOSE_ON_CLOSE JFrame.EXIT_ON_CLOSEJFrame.EXIT_ON_CLOSE Note: The close-window-button is part of the JFrame (not Note: The close-window-button is part of the JFrame (not

a JButton)a JButton) public void setSize ( int width, int height )public void setSize ( int width, int height )

Page 15: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

More useful JFrame methodsMore useful JFrame methods

public void setTitle ( String title )public void setTitle ( String title ) public void add ( Component componentAdded )public void add ( Component componentAdded ) public void setLayout ( LayoutManager manager )public void setLayout ( LayoutManager manager ) public void setJMenuBar ( JMenuBar menubar )public void setJMenuBar ( JMenuBar menubar ) public void dispose ( )public void dispose ( ) public void setVisible ( boolean makeVisible )public void setVisible ( boolean makeVisible )

Page 16: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

ButtonsButtons

via Swing’s JButtonvia Swing’s JButton

Page 17: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Buttons (JButton)Buttons (JButton)

Different kinds of components require Different kinds of components require different kinds of listener classes to handle the different kinds of listener classes to handle the events they fire.events they fire.

A button fires events known as action events, A button fires events known as action events, which are handled by listeners know as action which are handled by listeners know as action listeners.listeners.

Page 18: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Back to creating a window in SwingBack to creating a window in Swing

import javax.swing.JFrame;import javax.swing.JFrame;

……JFrame f = new JFrame( “My Simple Frame” );JFrame f = new JFrame( “My Simple Frame” );f.setSize( 300, 200 ); //w, hf.setSize( 300, 200 ); //w, hf.setDefaultCloseOperation(f.setDefaultCloseOperation(

JFrame.DO_NOTHING_ON_CLOSE );JFrame.DO_NOTHING_ON_CLOSE );……f.setVisible( true );f.setVisible( true );

This is not a very OO approach!

Page 19: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

A more OO approach to creating a A more OO approach to creating a window in Swingwindow in Swing

import javax.swing.JFrame;import javax.swing.JFrame;

public MyFrame public MyFrame extends JFrameextends JFrame { {public static final intpublic static final int sWidth = 300;sWidth = 300;public static final intpublic static final int sHeight = 200;sHeight = 200;MyFrame ( ) {MyFrame ( ) {

super( “My More OO Simple Frame” );super( “My More OO Simple Frame” );setSize( sWidth, sHeight );setSize( sWidth, sHeight );setDefaultCloseOperation(setDefaultCloseOperation(

JFrame.DO_NOTHING_ON_CLOSE );JFrame.DO_NOTHING_ON_CLOSE );……setVisible( true );setVisible( true );

}}……

}}

Page 20: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

JLabel – a line of textJLabel – a line of text

Simply a line of text appearing in a window.Simply a line of text appearing in a window.import javax.swing.JLabel;import javax.swing.JLabel;

……

JLabel label = new JLabel( “hello there.” );JLabel label = new JLabel( “hello there.” );

add( label );add( label );

Page 21: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Programming in ColorProgramming in Color

import java.awt.Color;import java.awt.Color;

……

Color.BLACKColor.BLACK AlsoAlso

Color.BLUE, Color.CYAN, Color.DARK_GRAY, …Color.BLUE, Color.CYAN, Color.DARK_GRAY, … Or you can specify/create your own colors by specifying Or you can specify/create your own colors by specifying

the argb or rgb values in the Color ctor.the argb or rgb values in the Color ctor. Use getContentPane().setBackground( Color.BLUE ); Use getContentPane().setBackground( Color.BLUE );

to change the background color of your JFrame.to change the background color of your JFrame.

Page 22: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Programming in colorProgramming in color

Colors are represented by their RGB value.Colors are represented by their RGB value. R=redR=red G=greenG=green B=blueB=blue When R is the largest value, the color has more red When R is the largest value, the color has more red

than the other components.than the other components. What happens when r=g=b?What happens when r=g=b?

Sometimes ARGB is used where A=alpha Sometimes ARGB is used where A=alpha (opacity).(opacity).

Page 23: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Layout ManagersLayout Managers

Page 24: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Controlling the placement of Controlling the placement of components in a container (our components in a container (our

frame)frame) So far, we simply add components to a container and accept So far, we simply add components to a container and accept

whatever default layout is presented.whatever default layout is presented. Layout manager – describes how the components are Layout manager – describes how the components are

arranged.arranged. Java provides many layout managers.Java provides many layout managers.

1.1. Border (in book)Border (in book)2.2. Box (not in book)Box (not in book)3.3. Card (not in book)Card (not in book)4.4. Flow (in book)Flow (in book)5.5. Grid (in book)Grid (in book)6.6. Grid bag (not in book)Grid bag (not in book)7.7. Group (not in book)Group (not in book)8.8. Spring (not in book)Spring (not in book)

Page 25: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

BorderLayoutBorderLayout

Places the components in five areas:Places the components in five areas:1.1. NorthNorth

2.2. SouthSouth

3.3. EastEast

4.4. WestWest

5.5. CenterCenter You specify the area in the add method.You specify the area in the add method.

add( new JLabel(“me”), BorderLayout.NORTH );add( new JLabel(“me”), BorderLayout.NORTH );

Page 26: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Using the BorderLayoutUsing the BorderLayout

import java.awt.BorderLayout;import java.awt.BorderLayout;import javax.swing.JFrame;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JLabel;

public class MyFrame extends JFrame {public class MyFrame extends JFrame {public MyFrame ( ) {public MyFrame ( ) {

super( “My frame w/ border layout.” );super( “My frame w/ border layout.” );setSize( 300, 200 );setSize( 300, 200 );setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );setLayout( setLayout( new BorderLayout()new BorderLayout() ); );add( new JLabel( “first” ), add( new JLabel( “first” ), BorderLayout.NORTHBorderLayout.NORTH ); );add( new JLabel( “second” ), add( new JLabel( “second” ), BorderLayout.SOUTHBorderLayout.SOUTH ); );……setVisible( true );setVisible( true );

}}}}

Page 27: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

FlowLayoutFlowLayout

Simplest.Simplest.

Arranges components one after another, from Arranges components one after another, from left to right and top to bottom, in the order in left to right and top to bottom, in the order in which one adds them.which one adds them.

Page 28: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Using the FlowLayoutUsing the FlowLayout

import java.awt.FlowLayout;import java.awt.FlowLayout;import javax.swing.JButton;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JLabel;

public class MyFrame extends JFrame {public class MyFrame extends JFrame {public MyFrame ( ) {public MyFrame ( ) {

super( “My frame w/ flow layout.” );super( “My frame w/ flow layout.” );setSize( 300, 200 );setSize( 300, 200 );setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );setLayout( setLayout( new FlowLayout()new FlowLayout() ); );add( new JLabel( “first” ) );add( new JLabel( “first” ) );add( new JButton( “second” ) );add( new JButton( “second” ) );……setVisible( true );setVisible( true );

}}}}

Page 29: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

GridLayoutGridLayout

Arranges components Arranges components on a 2D grid of given on a 2D grid of given size (i.e., rows and size (i.e., rows and cols specified via the cols specified via the GridLayout ctor).GridLayout ctor).

Each entry in the grid Each entry in the grid will be stretched to will be stretched to the the samesame size. size.

Page 30: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Placement rules are more complicated.Placement rules are more complicated. Say we have a 2 x 3 (2 rows x 3 cols):Say we have a 2 x 3 (2 rows x 3 cols):

new GridLayout( 2, 3 )new GridLayout( 2, 3 ) If we subsequently add six things, they will appear in a If we subsequently add six things, they will appear in a

2x3 grid of equally sized elements.2x3 grid of equally sized elements.

What happens if we add more or less?What happens if we add more or less?

GridLayoutGridLayout

Page 31: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

GridLayoutGridLayout

Placement rules are more Placement rules are more complicated.complicated. Say we have a 2 x 3 (2 rows Say we have a 2 x 3 (2 rows

x 3 cols).x 3 cols).

Adding 7 or 8 items causes Adding 7 or 8 items causes a col to be added.a col to be added.

Adding fewer than 6 items Adding fewer than 6 items causes a col(s) to be deleted.causes a col(s) to be deleted.

X

Page 32: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

GridLayoutGridLayout

Placement rules are more complicated.Placement rules are more complicated. Say we have a 2 x 3 (2 rows x 3 cols).Say we have a 2 x 3 (2 rows x 3 cols).

To only honor the number of rows, specify a 0 for To only honor the number of rows, specify a 0 for the cols.the cols.

To honor only the number of cols, specify a 0 for To honor only the number of cols, specify a 0 for the rows.the rows.

Page 33: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Using the GridLayoutUsing the GridLayout

import java.awt.GridLayout;import java.awt.GridLayout;import javax.swing.JButton;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JLabel;

public class MyFrame extends JFrame {public class MyFrame extends JFrame {public MyFrame ( ) {public MyFrame ( ) {

super( “My frame w/ flow layout.” );super( “My frame w/ flow layout.” );setSize( 300, 200 );setSize( 300, 200 );setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );setLayout( setLayout( new GridLayout(0,1)new GridLayout(0,1) ); //always a single col ); //always a single coladd( new JLabel( “first” ) );add( new JLabel( “first” ) );add( new JButton( “second” ) );add( new JButton( “second” ) );……setVisible( true );setVisible( true );

}}}}

Page 34: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Summary of Layout ManagersSummary of Layout Managers

FlowLayoutFlowLayout Displays components from left to right in the order Displays components from left to right in the order

in which they are added to the container.in which they are added to the container. BorderLayoutBorderLayout

Displays the components in five areas: N, S, E, W, Displays the components in five areas: N, S, E, W, and Center. You specify the area in the add and Center. You specify the area in the add method.method.

GridLayoutGridLayout Lays out components in a grid with each Lays out components in a grid with each

component stretched to fill its box in the grid.component stretched to fill its box in the grid.

Page 35: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Additional Layout ManagersAdditional Layout Managers

Box (not in book)Box (not in book) Card (not in book)Card (not in book) Tabbed pane (not in book; not strictly a layout Tabbed pane (not in book; not strictly a layout

manager)manager) Grid bag (not in book)Grid bag (not in book) Group (not in book)Group (not in book) Spring (not in book)Spring (not in book)

Page 36: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

BoxLayoutBoxLayout

““either stacks its components on top of each other or either stacks its components on top of each other or places them in a row - your choice” from places them in a row - your choice” from http://java.sun.com/docs/books/tutorial/uiswing/layout/bhttp://java.sun.com/docs/books/tutorial/uiswing/layout/box.htmlox.html

Page 37: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

CardLayoutCardLayout

Typically used to switch between different Typically used to switch between different panels.panels.

Poor man’s version of tabbed pane.Poor man’s version of tabbed pane.choice here

causes change here

Page 38: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

JTabbedPaneJTabbedPane

Not strictly a layout manager.Not strictly a layout manager. Typically preferred over CardLayout.Typically preferred over CardLayout.

Page 39: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

GridBagLayoutGridBagLayout

“… “… if you want to code by hand and do not want to use GroupLayout, then 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 GridBagLayout is recommended as the next most flexible and powerful layout manager” from layout manager” from http://java.sun.com/docs/books/tutorial/uiswing/layout/card.htmlhttp://java.sun.com/docs/books/tutorial/uiswing/layout/card.html

Page 40: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

GroupLayoutGroupLayout

“… “… if you want to code by hand and do not want to use GroupLayout, then 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 GridBagLayout is recommended as the next most flexible and powerful layout manager” from layout manager” from http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html

Intended to be used by a GUI builder.Intended to be used by a GUI builder.

Page 41: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

SpringLayoutSpringLayout

Intended to be used by GUI builder.Intended to be used by GUI builder.

Page 42: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

JPanelJPanel

a general purpose window-like a general purpose window-like containercontainer

Page 43: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Panels (JPanel)Panels (JPanel)

General purpose, window-like containerGeneral purpose, window-like container Groups objectsGroups objects Components may be added to them (including Components may be added to them (including

other panels)other panels) hierarchicalhierarchical

Layout manager can be associated w/ a panelLayout manager can be associated w/ a panel Can be added to a JFrameCan be added to a JFrame

Page 44: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Example JPanelsExample JPanelsJPanel 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

Page 45: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

COMPLETE JPANEL COMPLETE JPANEL EXAMPLEEXAMPLE

Page 46: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

JPanel exampleJPanel example

Let’s create a window with 3 Let’s create a window with 3 panels with the default panels with the default background color, and 3 background color, and 3 buttons, red, white, and blue.buttons, red, white, and blue.

When a button is pressed, the When a button is pressed, the corresponding panel will corresponding panel will change to that color.change to that color.

Page 47: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

JPanel exampleJPanel example

GridLayout (center)GridLayout (center)

FlowLayout (south)FlowLayout (south)

Page 48: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

JPanel ExampleJPanel Exampleimport javax.swing.JFrame;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JPanel;import java.awt.BorderLayout;import java.awt.BorderLayout;import java.awt.GridLayout;import java.awt.GridLayout;import java.awt.FlowLayout;import java.awt.FlowLayout;import java.awt.Color;import java.awt.Color;import javax.swing.JButton;import javax.swing.JButton;import java.awt.event.ActionListener;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import java.awt.event.ActionEvent;

public class PanelDemo extends JFrame public class PanelDemo extends JFrame implements ActionListenerimplements ActionListener

{{ public static final int WIDTH = 300;public static final int WIDTH = 300; public static final int HEIGHT = 200;public static final int HEIGHT = 200;

private JPanel redPanel = new JPanel();private JPanel redPanel = new JPanel(); private JPanel whitePanel = new JPanel();private JPanel whitePanel = new JPanel(); private JPanel bluePanel = new JPanel();private JPanel bluePanel = new JPanel();

public static void main ( String[] args ) {public static void main ( String[] args ) { PanelDemo gui = new PanelDemo( );PanelDemo gui = new PanelDemo( ); gui.setVisible( true );gui.setVisible( true ); }}

public void actionPerformed ( ActionEvent e ) {public void actionPerformed ( ActionEvent e ) { String buttonString = e.getActionCommand();String buttonString = e.getActionCommand();

if (buttonString.equals("Red"))if (buttonString.equals("Red")) redPanel.setBackground( Color.RED );redPanel.setBackground( Color.RED ); else if (buttonString.equals("White"))else if (buttonString.equals("White")) whitePanel.setBackground(Color.WHITE);whitePanel.setBackground(Color.WHITE); else if (buttonString.equals("Blue"))else if (buttonString.equals("Blue")) bluePanel.setBackground( Color.BLUE );bluePanel.setBackground( Color.BLUE ); elseelse System.out.println( "Unexpected error." );System.out.println( "Unexpected error." ); }}

Page 49: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

JPanel ExampleJPanel Example public PanelDemo ( ) {public PanelDemo ( ) { super( "Panel Demonstration“ );super( "Panel Demonstration“ ); setSize( WIDTH, HEIGHT );setSize( WIDTH, HEIGHT ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setLayout( new BorderLayout( ) );setLayout( new BorderLayout( ) );

JPanel biggerPanel = new JPanel( );JPanel biggerPanel = new JPanel( ); biggerPanel.setLayout( new GridLayout(1, 3) );biggerPanel.setLayout( new GridLayout(1, 3) );

redPanel.setBackground( Color.LIGHT_GRAY );redPanel.setBackground( Color.LIGHT_GRAY ); biggerPanel.add( redPanel );biggerPanel.add( redPanel );

whitePanel.setBackground( Color.LIGHT_GRAY );whitePanel.setBackground( Color.LIGHT_GRAY ); biggerPanel.add( whitePanel );biggerPanel.add( whitePanel );

bluePanel.setBackground( Color.LIGHT_GRAY );bluePanel.setBackground( Color.LIGHT_GRAY ); biggerPanel.add( bluePanel );biggerPanel.add( bluePanel );

add( biggerPanel, BorderLayout.CENTER );add( biggerPanel, BorderLayout.CENTER );

JPanel buttonPanel = new JPanel( );JPanel buttonPanel = new JPanel( ); buttonPanel.setBackground( Color.LIGHT_GRAY );buttonPanel.setBackground( Color.LIGHT_GRAY ); buttonPanel.setLayout( new FlowLayout( ) );buttonPanel.setLayout( new FlowLayout( ) );

JButton redButton = new JButton( "Red" );JButton redButton = new JButton( "Red" ); redButton.setBackground( Color.RED );redButton.setBackground( Color.RED ); redButton.addActionListener( this );redButton.addActionListener( this ); buttonPanel.add( redButton );buttonPanel.add( redButton );

JButton whiteButton = new JButton( "White" );JButton whiteButton = new JButton( "White" ); whiteButton.setBackground( Color.WHITE );whiteButton.setBackground( Color.WHITE ); whiteButton.addActionListener( this );whiteButton.addActionListener( this ); buttonPanel.add( whiteButton );buttonPanel.add( whiteButton );

JButton blueButton = new JButton( "Blue" );JButton blueButton = new JButton( "Blue" ); blueButton.setBackground( Color.BLUE );blueButton.setBackground( Color.BLUE ); blueButton.addActionListener( this );blueButton.addActionListener( this ); buttonPanel.add( blueButton );buttonPanel.add( blueButton );

add( buttonPanel, BorderLayout.SOUTH );add( buttonPanel, BorderLayout.SOUTH ); setVisible( true );setVisible( true ); }}}}

Page 50: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

JPanel ExampleJPanel Example

PanelDemo (JFrame w/ BorderLayout)PanelDemo (JFrame w/ BorderLayout) biggerPanel (w/ GridLayout of 1 row & 3 cols)biggerPanel (w/ GridLayout of 1 row & 3 cols)

added at centeradded at center redPanelredPanel whitePanelwhitePanel bluePanelbluePanel

buttonPanel (w/ FlowLayout)buttonPanel (w/ FlowLayout) added at southadded at south redButtonredButton whiteButtonwhiteButton blueButtonblueButton

Page 51: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

The Container classThe Container class

Can have components added to itCan have components added to it JFrame & JPanel are descendents of ContainerJFrame & JPanel are descendents of Container Container class = any descendent of ContainerContainer class = any descendent of Container Component = any descendent of JComponentComponent = any descendent of JComponent You may add any component to any containerYou may add any component to any container JComponent is derived from Container so you JComponent is derived from Container so you

may add a JComponent to a JComponentmay add a JComponent to a JComponent

Page 52: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

More examplesMore examples

Page 53: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

The MVC PatternThe MVC Pattern

MVC = Model+View+ControllerMVC = Model+View+Controller

Page 54: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Model-View-Controller (from Model-View-Controller (from wikipedia.org)wikipedia.org)

ModelModel The domain-specific representation of the information on The domain-specific representation of the information on

which the application operates. Domain logic adds which the application operates. Domain logic adds meaning to raw data (e.g., calculating whether today is the meaning to raw data (e.g., calculating whether today is the user's birthday, or the totals, taxes, and shipping charges user's birthday, or the totals, taxes, and shipping charges for shopping cart items).for shopping cart items).

Many applications use a persistent storage mechanism Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not (such as a database) to store data. MVC does not specifically mention the data access layer because it is specifically mention the data access layer because it is understood to be underneath or encapsulated by the Model.understood to be underneath or encapsulated by the Model.

Page 55: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Model-View-Controller (from Model-View-Controller (from wikipedia.org)wikipedia.org)

ViewView Renders the model into a form suitable for interaction, Renders the model into a form suitable for interaction,

typically a user interface element.typically a user interface element.

Multiple views can exist for a single model for different Multiple views can exist for a single model for different purposes.purposes.

Page 56: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Model-View-Controller (from Model-View-Controller (from wikipedia.org)wikipedia.org)

ControllerController Processes and responds to events, typically user actions, Processes and responds to events, typically user actions,

and may invoke changes on the model. and may invoke changes on the model.

Page 57: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Basic MVCBasic MVCModel

data1

data2

.

.

.

View

update()

Controller

manipulatenotify

Page 58: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Model-View-Controller (from Model-View-Controller (from wikipedia.org)wikipedia.org)

Though MVC comes in different flavors, control flow generally works as Though MVC comes in different flavors, control flow generally works as follows:follows:

1.1. The user interacts with the user interface in some way (e.g., presses a button).The user interacts with the user interface in some way (e.g., presses a button).

2.2. A controller handles the input event from the user interface, often via a A controller handles the input event from the user interface, often via a registered handler or callback.registered handler or callback.

3.3. The controller accesses the model, possibly updating it in a way appropriate 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).to the user's action (e.g., controller updates user's shopping cart).

4.4. A view uses the model (indirectly) to generate an appropriate user interface 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 (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 gets its own data from the model. The model has no direct knowledge of the view.view.

5.5. The user interface waits for further user interactions, which begins the cycle The user interface waits for further user interactions, which begins the cycle anew.anew.

By decoupling models and views, MVC helps to reduce the complexity in By decoupling models and views, MVC helps to reduce the complexity in architectural design, and to increase flexibility and reuse.architectural design, and to increase flexibility and reuse.

Page 59: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Model-View-Controller (from Model-View-Controller (from wikipedia.org)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).

Page 60: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Observer patternObserver pattern

““The observer pattern is a software design pattern in The observer pattern is a software design pattern in which an object, called the subject, maintains a list which an object, called the subject, maintains a list of its dependents, called observers, and notifies of its dependents, called observers, and notifies them automatically of any state changes, usually by them automatically of any state changes, usually by calling one of their methods. It is mainly used to calling one of their methods. It is mainly used to implement distributed event handling systems.”implement distributed event handling systems.”

from http://en.wikipedia.org/wiki/Observer_patternfrom http://en.wikipedia.org/wiki/Observer_pattern

Page 61: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

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).

Page 62: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

NoteNote

Some designers combine/simply the M-V-C to Some designers combine/simply the M-V-C to D-V where…D-V where… D is the document, data, or model,D is the document, data, or model, V is the View, andV is the View, and the controller is typically part of the view.the controller is typically part of the view.

Page 63: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Menus and buttonsMenus and buttons

Page 64: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Menu bars, menus, and menu itemsMenu bars, menus, and menu items

JMenuBar, JMenu, and JMenuItemJMenuBar, JMenu, and JMenuItem import:import:

javax.swing.JMenuBarjavax.swing.JMenuBar ex. the menu bar in an appex. the menu bar in an app

javax.swing.JMenujavax.swing.JMenu ex. Fileex. File ex. Editex. Edit ex. Helpex. Help

javax.swing.JMenuItemjavax.swing.JMenuItem ex. Open in the File menuex. Open in the File menu ex. Cut in the Edit menuex. Cut in the Edit menu

implement ActionListener for eventsimplement ActionListener for events

Page 65: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

ExampleExample

menu bar

menu

menu item

Page 66: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Example: creating a menu barExample: creating a menu bar

……public class MenuDemo extends JFrame implements ActionListener {public class MenuDemo extends JFrame implements ActionListener {

……public MenuDemo ( ) {public MenuDemo ( ) {

……JMenu colorMenu = new JMenu( “Add colors” );JMenu colorMenu = new JMenu( “Add colors” );

JMenuItem greenChoice = new JMenuItem( “Green” );JMenuItem greenChoice = new JMenuItem( “Green” );greenChoice.addActionListener( this );greenChoice.addActionListener( this );colorMenu.add( greenChoice );colorMenu.add( greenChoice );……JMenuBar bar = new JMenuBar();JMenuBar bar = new JMenuBar();bar.add( colorMenu );bar.add( colorMenu );setJMenuBar( bar );setJMenuBar( bar );

}}……

}}

Page 67: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Handling menu eventsHandling menu events

When we create a button or menu item, we When we create a button or menu item, we specify a string.specify a string.

By default, that string becomes the action By default, that string becomes the action command for that button.command for that button.

The action command is provided to the The action command is provided to the actionPerformed method.actionPerformed method.

The action command can be changed via The action command can be changed via setActionCommand (there is also a setActionCommand (there is also a getActionCommand method as well).getActionCommand method as well).

Page 68: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Example: handle menu eventsExample: handle menu events

……public class MenuDemo extends JFrame implements ActionListener {public class MenuDemo extends JFrame implements ActionListener {

……public void actionPerformed ( ActionEvent e ) {public void actionPerformed ( ActionEvent e ) {

String action = e.getActionCommand();String action = e.getActionCommand();if (action.equals( “Green” ))if (action.equals( “Green” ))

greenPanel.setBackground( Color.GREEN );greenPanel.setBackground( Color.GREEN );else if (action.equals( “White” )else if (action.equals( “White” )

whitePanel.setBackground( Color.WHITE );whitePanel.setBackground( Color.WHITE );……elseelse

System.out.println( “Unexpected action” );System.out.println( “Unexpected action” );}}……

}}

Page 69: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Advanced topic: sub/nested menusAdvanced topic: sub/nested menus

submenu

Page 70: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

submenussubmenus

Similarly to adding menu items to a menu, we Similarly to adding menu items to a menu, we may also add menus to menus. (Note that may also add menus to menus. (Note that JMenuItem is a superclass of JMenu below.)JMenuItem is a superclass of JMenu below.)

Page 71: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Text fields and text areasText fields and text areas

Page 72: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Text field (JTextField)Text field (JTextField) A field that allows the user to enter a single line of A field that allows the user to enter a single line of

text.text. Ex.Ex.

JTextField name = new JTextField( 30 );JTextField name = new JTextField( 30 );……String inputString = name.getText();String inputString = name.getText();……name.setText( “fred” );name.setText( “fred” );

JTextField f2 = new JTextField( “ethel”, 30 ); //default JTextField f2 = new JTextField( “ethel”, 30 ); //default valuevalue

30 is the minimum number of visible characters (more may 30 is the minimum number of visible characters (more may be entered)be entered)

Page 73: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Text area (JTextArea)Text area (JTextArea)

Same as text field except it allows multiple lines.Same as text field except it allows multiple lines. Ex.Ex.

JTextArea theText = new JTextArea( 5, 20 );JTextArea theText = new JTextArea( 5, 20 );

JTextArea t2 = new JTextArea( “hello\nthere”, 5, 20 );JTextArea t2 = new JTextArea( “hello\nthere”, 5, 20 );

5 is the minimum number of visible lines.5 is the minimum number of visible lines.

20 is the minimum number of visible characters.20 is the minimum number of visible characters.

Page 74: Graphical User Interface Programming. GUI Graphical User Interface Graphical User Interface event driven programming event driven programming Java GUI

Some useful JTextComponent Some useful JTextComponent methodsmethods

public String getText()public String getText()

public boolean isEditable()public boolean isEditable()

public void setBackground ( Color theColor )public void setBackground ( Color theColor )

public void setEditable ( boolean argument )public void setEditable ( boolean argument )

public void setText ( String text )public void setText ( String text )