java programming introduction to swing class 7. swing graphical user interface provides windows...

63
Java Programming Introduction to Swing Class 7

Upload: dwight-gilbert

Post on 05-Jan-2016

221 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Java Programming

Introduction to SwingClass 7

Page 2: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Swing Graphical User Interface

Provides Windows Menus Buttons Labels Textboxes

In the beginning, there was AWT …. Abstract Windowing Toolkit

Relied on peers Heavyweight Native Code interfaces

Written for each target Enabled original AWT to be written in 6 weeks! Portability problems

Page 3: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

A Swing Program import java.awt.*; import javax.swing.*; public class JWTest { static final int n_label = 10; public static void main( String args[] ) { JLabel[] lab1; Jwindow w = new JWindow(); Container content_pane = w.getContentPane(); w.setVisible( true ); content_pane.setLayout( new BorderLayout( ) ); lab1 = new JLabel[n_label]; for(int k=0;k<n_label;k++) { lab1[k] = new JLabel("Label " + k); content_pane.add( lab1[k] ); } w.pack(); w.show(); System.exit(0); } }

Page 4: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

A Swing Programimport java.awt.*;import javax.swing.*;public class JWTest {static final int n_label = 10;public static void main( String args[] ) {JLabel[] lab1;Jwindow w = new JWindow();Container content_pane = w.getContentPane();w.setVisible( true );content_pane.setLayout( new BorderLayout( ) );lab1 = new JLabel[n_label];for(int k=0;k<n_label;k++) {lab1[k] = new JLabel("Label " + k);content_pane.add( lab1[k] );}w.pack();w.show();System.exit(0);}}

import java.awt.*;import javax.swing.*;

Import classes fromjava.awt

javax.swingpackages

The * implies import all classes in the packageYou could importsome parts of a package,but few seem to be keento type out lists of names!

Swing is built onjava.awt

You can mix them …Not recommended though!

Page 5: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

A Swing Program

import java.awt.*;import javax.swing.*;public class JWTest {static final int n_label = 10;public static void main( String args[] ) {JLabel[] lab1;Jwindow w = new JWindow();Container content_pane = w.getContentPane();w.setVisible( true );content_pane.setLayout( new BorderLayout( ) );lab1 = new JLabel[n_label];for(int k=0;k<n_label;k++) {lab1[k] = new JLabel("Label " + k);content_pane.add( lab1[k] );}w.pack();w.show();System.exit(0);}}

public class JWTest { … public static void main( String args[] ) { … }

}

Programs are classes!

The main method enablesthis class to run as a stand-alone application

Page 6: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Constants

import java.awt.*;import javax.swing.*;public class JWTest {static final int n_label = 10;public static void main( String args[] ) {JLabel[] lab1;Jwindow w = new JWindow();Container content_pane = w.getContentPane();w.setVisible( true );content_pane.setLayout( new BorderLayout( ) );lab1 = new JLabel[n_label];for(int k=0;k<n_label;k++) {lab1[k] = new JLabel("Label " + k);content_pane.add( lab1[k] );}w.pack();w.show();System.exit(0);}}

static final int n_label = 10;

Java’s method of providing a constant

finalYou can’t change thevalue

Each object acquires an instance of other variablesdeclared in this area!

static There’s only one instanceof this variablefor the whole class

Page 7: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Arrays

import java.awt.*;import javax.swing.*;public class JWTest {static final int n_label = 10;public static void main( String args[] ) {JLabel[] lab1;JWindow w = new JWindow();Container content_pane = w.getContentPane();w.setVisible( true );content_pane.setLayout( new BorderLayout( ) );lab1 = new JLabel[n_label];for(int k=0;k<n_label;k++) {lab1[k] = new JLabel("Label " + k);content_pane.add( lab1[k] );}w.pack();w.show();System.exit(0);}}

JLabel[] lab1;…lab1 = new JLabel[n_label];

Declare an array of labels

Note the J prefixfor Swing classes(awt has Label)

Construct an instance ofthe array with n_labelelements

Page 8: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Construct a window

import java.awt.*;import javax.swing.*;public class JWTest {static final int n_label = 10;public static void main( String args[] ) {JLabel[] lab1;JWindow w = new JWindow();Container content_pane = w.getContentPane();w.setVisible( true );content_pane.setLayout( new BorderLayout( ) );lab1 = new JLabel[n_label];for(int k=0;k<n_label;k++) {lab1[k] = new JLabel("Label " + k);content_pane.add( lab1[k] );}w.pack();w.show();System.exit(0);}}

JWindow w = new JWindow();

Declare a JWindowa stand-alone window

Initialise it immediatelyby calling the JWindowconstructor with new

Page 9: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Where can I draw things?

import java.awt.*;import javax.swing.*;public class JWTest {static final int n_label = 10;public static void main( String args[] ) {JLabel[] lab1;JWindow w = new JWindow();Container content_pane = w.getContentPane();w.setVisible( true );content_pane.setLayout( new BorderLayout( ) );lab1 = new JLabel[n_label];for(int k=0;k<n_label;k++) {lab1[k] = new JLabel("Label " + k);content_pane.add( lab1[k] );}w.pack();w.show();System.exit(0);}}

Container content_pane = w.getContentPane();

You can’t draw in the JWindow itselfYou must get one of its content

panes(it has three)

and draw in that!

The panes are Container sYou can add things to them

Here we apply the getContentPane()method to the windowto return itscontent pane

Page 10: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Panes?

There are 3 of them contentPane

JPanel Resides in layeredPane Contains components

glassPane JPanel ‘Floats’ above others Traps mouse events first

layeredPane JLayeredPane Contains contentPane and menuBar

menuBar JMenuBar

Page 11: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Visibility and Layout

import java.awt.*;import javax.swing.*;public class JWTest {static final int n_label = 10;public static void main( String args[] ) {JLabel[] lab1;JWindow w = new JWindow();Container content_pane = w.getContentPane();w.setVisible( true );content_pane.setLayout( new BorderLayout( ) );lab1 = new JLabel[n_label];for(int k=0;k<n_label;k++) {lab1[k] = new JLabel("Label " + k);content_pane.add( lab1[k] );}w.pack();w.show();System.exit(0);}}

w.setVisible( true );content_pane.setLayout( new BorderLayout( ) );

Make the window visible(One of the major challenges in Java ..

Getting your components to reveal themselves ..They’re often extremely shy! )

The arrangement of componentsin a Container is determined by a Layout Manager

BorderLayout()- one of the layoutmanagersMore soon ..

Page 12: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Adding things to a window

import java.awt.*;import javax.swing.*;public class JWTest {static final int n_label = 10;public static void main( String args[] ) {JLabel[] lab1;Jwindow w = new JWindow();Container content_pane = w.getContentPane();w.setVisible( true );content_pane.setLayout( new BorderLayout( ) );lab1 = new JLabel[n_label];for(int k=0;k<n_label;k++) {lab1[k] = new JLabel("Label " + k);content_pane.add( lab1[k] );}w.pack();w.show();System.exit(0);}}

for(int k=0;k<n_label;k++) { lab1[k] = new JLabel("Label " + k); content_pane.add( lab1[k] ); }

Add them to the content pane

Create the labels

Page 13: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Some Java features

import java.awt.*;import javax.swing.*;public class JWTest {static final int n_label = 10;public static void main( String args[] ) {JLabel[] lab1;Jwindow w = new JWindow();Container content_pane = w.getContentPane();w.setVisible( true );content_pane.setLayout( new BorderLayout( ) );lab1 = new JLabel[n_label];for(int k=0;k<n_label;k++) {lab1[k] = new JLabel("Label " + k);content_pane.add( lab1[k] );}w.pack();w.show();System.exit(0);}}

for(int k=0;k<n_label;k++) { lab1[k] = new JLabel("Label " + k); content_pane.add( lab1[k] ); }

k is an int ...but Java will convert itto its string representation

+ Creates a stringby concatenatingits arguments

Page 14: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Almost there ...

import java.awt.*;import javax.swing.*;public class JWTest {static final int n_label = 10;public static void main( String args[] ) {JLabel[] lab1;Jwindow w = new JWindow();Container content_pane = w.getContentPane();w.setVisible( true );content_pane.setLayout( new BorderLayout( ) );lab1 = new JLabel[n_label];for(int k=0;k<n_label;k++) {lab1[k] = new JLabel("Label " + k);content_pane.add( lab1[k] );}w.pack();w.show();System.exit(0);}}

w.pack();w.show();System.exit(0);

Pack the components into theminimum size window

Finished,so exit

Show the window

Page 15: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Those labels are boring ...

Changing them … Swing API

Documentation cached at ..http://www.javasoft.com

Observe the hierarchyObjectComponent

ContainerJComponentJLabel

Page 16: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Those labels are boring ... Changing them … Note the specification

public class JLabel extends JComponent implements SwingConstants,

AccessibleJComponent is theimmediate ‘ancestor’or superclass

JLabel providesthe methods in theseinterfaces

Page 17: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Those labels are boring ... Look for methods that ‘operate’ on JLabel

Note that most of them don’t have arguments They operate on a JLabel

Icon getIcon();int getHorizontalAlignment();int getHorizontalTextPosition();String getText();void setText( String text ); … … etc

JLabel label = new JLabel(“Test label”);Icon img = label.getIcon();

Page 18: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

But I want to change the text font! Look for methods on the superclasses On JComponent

Since a JLabel is also a Jcomponent ..

works fine!

void setFont( Font font );

Jlabel label = new Jlabel(“Test label”);label.setFont( newfont );

Page 19: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

and I want to change the location .. Look for methods on the superclasses On JComponent

?? Nothing likely Try the next ancestor .. On Container

?? Nothing likely On Component

looks promising ... But there’s two???

works fine!

setLocation

Page 20: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Polymorphism in practice ... But there’s two ….. !!

Choose the most convenient

the compiler determines which one to use by matching the signature ..

void setLocation( int x, int y );void setLocation( Point p );label.setLocation( X_POS, Y_POS );

void setLocation( int, int );

return type namenumber of arguments

types of arguments

Page 21: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Polymorphism in practice ... Multiple Constructors

Common situation

Again choose the most convenient Other attribute values will assume default

values, eg No icon, centre alignment

JLabel();JLabel( Icon image );JLabel( Icon image, int horAlign );JLabel( String text );JLabel( String text, Icon image, int horAloginJLabel( String text, int horAlign );

Page 22: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Other common components Buttons

JButton ‘Standard’ way for initiating some action from a screen Used with an ActionListener (next lecture!)

JToggleButton Two states: selected / de-selected Query with

boolean isSelected() ButtonGroup

Found in the parent AbstractButton!! Allows groups of buttons Select one

Automatic de-select of remainder

Page 23: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Other common components

Buttons JCheckBox

Checked box .. Selected / Not selected It’s a specialization of JToggleButton!

JRadioButton Similar to JCheckBox

Page 24: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Frames & Applets JFrame

Specialization of Frame Adds

Border Menubar Close box

JApplet Similar to JFrame

Both have ContentPane GlassPane

Page 25: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Panels

JPanel Useful as a container for other

elements Window, Frame or Applet

Panel2Panel1

Buttonin Panel1

Buttonin Panel2

Page 26: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Panels

JPanel Useful as a container for other

elements

Panel2Panel1

Buttonin Panel1

Buttonin Panel2

JWindow w = new JWindow();JPanel panel1 = new JPanel();JPanel panel2 = new JPanel();JButton b1 = new JButton();panel1.add( b1 );w.add( panel1 );panel2.add( b2 );w.add( panel2 );

Page 27: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Panels

JPanel Make the panels classes!

Panel2Panel1

Buttonin Panel1

Buttonin Panel2

public class Panel1 extends JPanel { public Panel1() { JButton b = new JButton(“b1”); add(b); }} public class PanelledWindow extends JWindow {

public PanelledWindow() { super(); Panel1 p1 = new Panel1(); Panel2 p2 = new Panel2(); w.add(p1); w.add(p2); }}

Page 28: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Text - Edit for user input

JTextField Single line of editable text

public class TextExample extends JPanel { JTextField tf;

public TextExample( String s ) { tf = new JTextField( s ); add( tf );

} public String getText() {

return tf.getText();

}

}

Check the text content(has a user has edited it?)

Page 29: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Text - Edit for user input

JTextArea Multiple lines of editable text

public class TextExample extends JPanel { JTextArea ta;

static final int rows = 10; static final int cols = 20; public TextExample( String s ) { ta = new JTextArea( s, rows, cols );

add( ta ); } public String getText( int row ) { int offset = ta.getLineStartOffset( row );

return tf.getText( offset, cols ); } } Check the text content

(has a user has edited it?)

Page 30: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Menus Menus are attached to a JMenuBar A Menu(JMenu)contains items (JMenuItem)

Recipe Create a frame Create a menubar

Create a menu Create some menu items Add an ActionListener

(next lecture!) Add them to the menu Add the menu to the menubar

Set the menubar

Repeat as needed

Page 31: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Menus

Example Create a frame Create a menubar Create a menu Create

some menu items Trap events Add them

to the menu Add the menu

to the menubar Set the menubar

JFrame f = new JFrame(“MenuT”);JMenuBar mb = new JMenuBar();JMenu menu = new JMenu(“Choose”);JMenuItem item1, item2;item1 = new JMenuItem(“Data 1”);item2 = new JMenuItem(“Data 2”); // Action listeners!!menu.add(item1);menu.add(item2);mb.add( menu );f.setJMenuBar( mb );

Page 32: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Swing Example Jwindow

Simple usage example import javax.swing.*;public class windowexample {

public static void main(String[] args) { JWindow w; JLabel label; int n; w = new JWindow(); label = new JLabel(“Example label”); w.add( label ); n = w.getComponentCount(); System.out.println(“Window has “ + n + “components”); w.show(); }

Java programs have

a main method(more later!)Declarations

Construct a new JWindow

Call the add method

on wto add

the label to it

Use the getC..C.. Methodto find out how many

components the windowhasDiagnostics: You will need this System method!!

Show the window

Page 33: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Java ProgrammingSwing (continued)

10 mins break (not more)

Page 34: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Menus

Repeat as needed

Menus are attached to a JMenuBar A Menu(JMenu)contains items (JMenuItem)

Recipe Create a frame Create a menubar

Create a menu Create some menu items Add an ActionListener

(next lecture!) Add them to the menu Add the menu to the menubar

Set the menubar

Page 35: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Menus Example

Create a frame Create a menubar Create a menu Create

some menu items Trap events Add them

to the menu Add the menu

to the menubar Set the menubar

JFrame f = new JFrame(“MenuT”);JMenuBar mb = new JMenuBar();JMenu menu = new JMenu(“Choose”);JMenuItem item1, item2;item1 = new JMenuItem(“Data 1”);item2 = new JMenuItem(“Data 2”); // Action listeners!!menu.add(item1);menu.add(item2);mb.add( menu );f.setJMenuBar( mb );

Page 36: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

That’s all very pretty but ...

Our GUI needs some action! Add Listener’s to Components

Component fire events, Listeners trap them Various types of listeners ..

ActionListener MouseListener MenuListener and some more ...

Listeners are interfaces No code! Remember just a specification for methods

you must supply

Page 37: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Making a Listener - Method 1

Define a class implementing ActionListener

1 // Event Handlerimport java.awt.*;import java.awt.event.*;import javax.swing.*;

public class EventHandler implements ActionListener {JPanel parent;JComponent src;public EventHandler( JPanel m ) {

// Establish a link to my parentparent = m;}

// ActionListener interfacepublic void actionPerformed( ActionEvent e ) {

System.out.println("aP event " + e );src = (JComponent)(e.getSource());}

}

This class must provide the methods specified for

ActionListener

In this case, there’sonly one ..

actionPerformed

Page 38: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Making a Listener - Method 1

Define a class implementing ActionListener

// Event Handlerimport java.awt.*;import java.awt.event.*;import javax.swing.*;

public class EventHandler implements ActionListener {JPanel parent;JComponent src;public EventHandler( JPanel m ) {

// Establish a link to my parentparent = m;}

// ActionListener interfacepublic void actionPerformed( ActionEvent e ) {

System.out.println("aP event " + e );src = (JComponent)(e.getSource());}

}

This class must provide the methods specified for

ActionListener

Note that the methodmust be identical

to the specification!

All must match Name Return type Parameter List

Page 39: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Making a Listener - Method 1

Define a class implementing ActionListener

// Event Handlerimport java.awt.*;import java.awt.event.*;import javax.swing.*;

public class EventHandler implements ActionListener {JPanel parent;JComponent src;

public EventHandler( JPanel m ) {// Establish a link to my parentparent = m;}

// ActionListener interfacepublic void actionPerformed( ActionEvent e ) {

System.out.println("aP event " + e );src = (JComponent)(e.getSource());}

}

The constructor may beused to establish a link

to the objects trapping events

Here I’ve assumed that a component is embedded in a Jpanel,so I make sure the handler has a link to the panel it’s located in

Page 40: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Making a Listener - Method 1

Define a class implementing ActionListener

// Event Handlerimport java.awt.*;import java.awt.event.*;import javax.swing.*;

public class EventHandler implements ActionListener {JPanel parent;JComponent src;

public EventHandler( JPanel m ) {// Establish a link to my parentparent = m;}

// ActionListener interfacepublic void actionPerformed( ActionEvent e ) {

System.out.println("aP event " + e );src = (JComponent)(e.getSource());}

}

The constructor may beused to establish a link

to the objects trapping events

You can instantiate as many of these handlers as you like .. One per panel One per group of related objects One per component

Page 41: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Making a Listener - Method 1

Define a class implementing ActionListener

// Event Handlerimport java.awt.*;import java.awt.event.*;import javax.swing.*;

public class EventHandler implements ActionListener {JPanel parent;JComponent src;public EventHandler( JPanel m ) {

// Establish a link to my parentparent = m;}

// ActionListener interfacepublic void actionPerformed( ActionEvent e ) {

System.out.println("aP event " + e );src = (JComponent)(e.getSource());}

}

The interface method will becalled whenever the appropriate

event is fired by a componentto which a listener has been attached

Page 42: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Making a Listener - Method 1

Define a class implementing ActionListener

// Event Handlerimport java.awt.*;import java.awt.event.*;import javax.swing.*;

public class EventHandler implements ActionListener {JPanel parent;JComponent src;public EventHandler( JPanel m ) {

// Establish a link to my parentparent = m;}

// ActionListener interfacepublic void actionPerformed( ActionEvent e ) {

System.out.println("aP event " + e );src = (JComponent)(e.getSource());}

}

This method can (among other things!) Output messages Determine which component fired the event Call methods in other classes (eg the parent) Access this class’ instance variables … (anything else a class could do!)

Page 43: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Making a Listener - Method 1

Define a class implementing ActionListener

// Event Handlerimport java.awt.*;import java.awt.event.*;import javax.swing.*;

public class EventHandler implements ActionListener {JPanel parent;JComponent src;public EventHandler( JPanel m ) {

// Establish a link to my parentparent = m;}

// ActionListener interfacepublic void actionPerformed( ActionEvent e ) {

System.out.println("aP event " + e );src = (JComponent)(e.getSource());}

}

The argument is an ActionEvent A whole class on its own! Methods ... Determine which component fired the event

Object getSource() Determine the active command String getActionCommand() modal interfaces, eg button which changes from “Run” to “Stop” Find out which keys were pressed int getModifiers() Alt / Ctrl / Shift / etc

Page 44: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

… we’d better attach the listener to something!

An Action button import javax.swing.*;public class windowexample {

public static void main(String[] args) { JWindow w = new JWindow(); JButton b = new JButton(“Action!”); EventHandler h = new EventHandler( this ); Container cp = getContentPane(); cp.add( b ); b.addActionListener( h ); w.pack(); w.show(); }

Construct a new JWindow

Don’t forgetto get the

content pane!

Construct a JButton

Instantiate an event handler

Add the button to the window

Attach the event handlerto the button

Page 45: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

How does the listener talk to us??

Various possibilities Call a method on the “parent”

public class DataPanel extends JPanel { int x; // some user data here public DataPanel( ) { EventHandler h = new EventHandler( this ); …. // Create button, add to panel, add listener } public void incX( int dx ) { x = x + dx; } }

public class EventHandler implements ActionListener { DataPanel dp; public EventHandler( DataPanel dp ) { this.dp = dp; } public void actionPerformed( ActionEvent e ) {

dp.incX( 1 ); } }

Page 46: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

How does the listener talk to us??

Various possibilities Call a method in another class

public class DataSet { int x; // some user data here public DataSet( ) { …. // Create button, add to panel, add listener } public void incX( int dx ) { x = x + dx; } }

public class EventHandler implements ActionListener { DataSet ds; public EventHandler( DataSet ds ) { this.ds = ds; } public void actionPerformed( ActionEvent e ) {

ds.incX( 1 ); } }

Note: specific class here!Not very generic!

Page 47: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Define a class of objects which can be incremented Must provide a void incX( int ) method

A case for an interface!!

public class DataSet implements Incrementable { int x; // some user data here public DataSet( ) { …. // Create button, add to panel, add listener } public void incX( int dx ) { x = x + dx; } }

public class EventHandler implements ActionListener { Incrementable ds; public EventHandler( Incrementable ds ) { this.ds = ds; } public void actionPerformed( ActionEvent e ) {

ds.incX( 1 ); } }

Page 48: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

A case for an interface!! Define a class of objects which can be incremented

Must provide a void incX( int ) method The interface provides the signature for a

method (or methods - it can require many)

The class implements the method(s) in the interface

and any others that it needs!

public interface Incrementable { public void incX( int dx ) ; }

public class DataSet implements Incrementable { int x; // some user data here public DataSet( ) { …. // Create button, add to panel, add listener } public void incX( int dx ) { x = x + dx; } }

Page 49: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

A case for an interface!! A class may implement several interface

public interface Incrementable { public void incX( int dx ) ; }

public class DataSet implements Incrementable, Decrementable { int x; // some user data here public DataSet( ) { …. // Create button, add to panel, add listener } public void incX( int dx ) { x = x + dx; } public void decX( int dx ) { x = x - dx; }}

public interface Decrementable { public void decX( int dx ) ; }

Incrementable OK!

Decrementable OK!

Page 50: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

To make many common structures .. Look up tables, search trees

and perform common operations Sort, Match

We need to compare items .. A Comparable interface is part of java.lang

It has one method

Class implementor decides how objects of a class are ordered

May depend on some very complex rules!! So compareTo can only be implemented in specific

classes but there are many places where ordering is needed!!

Comparable ..

public interface Comparable { public int compareTo( Object obj ) ; // returns <0, 0, >0 // depending on whether this is <, ==, > obj }

Page 51: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Talking to the handler ... The handler class can update one of its attributes and

provide a method to access it

public class EventHandler implements ActionListener { boolean event_happened = false; public EventHandler( ) { } public void actionPerformed( ActionEvent e ) {

event_happened = true; } public boolean eventHappened() {

boolean x = event_happened;event_happened = false;return x;}

} The class can provide additional methods

… and many other possibilities, use your imagination!

The event handlercan access attributes

of its object(just like any other method)

Page 52: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Making a Listener - Method 2

Define a separate class is a pain! Too many files, overhead

No problem - make it an inner class

public class windowexample { int x; class EventHandler

implements ActionListener { // ActionListener interface

public void actionPerformed( ActionEvent e ) {x++;}

} public static void main(String[] args) { JWindow w = new JWindow(); JButton b = new JButton(“Action!”); EventHandler h = new EventHandler( this ); Container cp = getContentPane(); cp.add( b ); b.addActionListener( h ); …… }

Class defined inside

windowexample

Use it here justlike any other

class

Page 53: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Making a Listener - Method 2

Define a separate class is a pain! Too many files, too much overhead

No problem - make it an inner class

public class windowexample { int x; class EventHandler

implements ActionListener { // ActionListener interface

public void actionPerformed( ActionEvent e ) {x++;}

} public static void main(String[] args) { JWindow w = new JWindow(); JButton b = new JButton(“Action!”); EventHandler h = new EventHandler( this ); Container cp = getContentPane(); cp.add( b ); b.addActionListener( h ); …… }

Class defined inside

windowexample

It can accessattributes of theenclosing class

Page 54: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Making a Listener - Method 3

But that’s a whole class with only one method! I’m lazy!

No problem - make it an anonymous class

public class windowexample { int x; public static void main(String[] args) { JWindow w = new JWindow(); JButton b = new JButton(“Action!”); b.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) {

x++;}

} );

Container cp = getContentPane(); cp.add( b ); …… }

Page 55: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Making a Listener - Method 3

But that’s a whole class with only one method! I’m lazy!

No problem - make it an anonymous class

public class windowexample { int x; public static void main(String[] args) { JWindow w = new JWindow(); JButton b = new JButton(“Action!”); b.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) {

x++;}

} );

Container cp = getContentPane(); cp.add( b ); …… }

Call addActionListener

Create a button

Page 56: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Making a Listener - Method 3

But that’s a whole class with only one method! I’m lazy!

No problem - make it an anonymous class

public class windowexample { int x; public static void main(String[] args) { JWindow w = new JWindow(); JButton b = new JButton(“Action!”); b.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) {

x++;}

} );

Container cp = getContentPane(); cp.add( b ); …… }

Call addActionListener

Its argumentshould be an

ActionListenerobject

So createone

“on-the-fly”here

You don’t need to give this class a name ..Hence it’s anonymous!

Page 57: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Anonymous classes The syntax can be confusing!

public class windowexample { int x; public static void main(String[] args) { JWindow w = new JWindow(); JButton b = new JButton(“Action!”); b.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) {

x++;}

} );

Container cp = getContentPane(); cp.add( b ); …… }

We make a new objectby calling

its constructorpreceded by new

It’s an ActionListener -just put the name of the

interface here

Page 58: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Anonymous classes The syntax can be confusing!

public class windowexample { int x; public static void main(String[] args) { JWindow w = new JWindow(); JButton b = new JButton(“Action!”); b.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) {

x++;}

} );

Container cp = getContentPane(); cp.add( b ); …… }

The constructor doesn’t have anyarguments

but don’t forget the ( )

Normal class body in { … }

Page 59: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Anonymous classes The syntax can be confusing!

public class windowexample { int x; public static void main(String[] args) { JWindow w = new JWindow(); JButton b = new JButton(“Action!”); b.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) {

x++;}

} );

Container cp = getContentPane(); cp.add( b ); …… }

An ActionListener must provideactionPerformed

.. and we can still access attributesof the enclosing class

Page 60: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

Anonymous classes The syntax can be confusing!

public class windowexample { int x; public static void main(String[] args) { JWindow w = new JWindow(); JButton b = new JButton(“Action!”); b.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) {

x++;}

} );

Container cp = getContentPane(); cp.add( b ); …… }

We make a new objectby calling

its constructorpreceded by new

The constructor doesn’t have anyarguments

but don’t forget the ( )

Normal class body in { … }

Page 61: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

MouseListener interface Fine control of your GUI, but … 5 methods!

An interface must implement each one

Fine if you want special effects,but painful if you only want a click!

JButton b = new JButton(“Action!”);b.addMouseListener( new MouseListener() { public void mouseClicked(MouseEvent e) { … }

public void mouseEntered(MouseEvent e) { … }

public void mouseExited(MouseEvent e) { … }

public void mousePressed(MouseEvent e) { … }

public void mouseReleased(MouseEvent e) { … }

} );

Page 62: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

MouseListener interface 5 methods!

A classic case for an adapter! MouseAdapter is a class implementing

MouseListener Provides dummy implementations for all 5 required

methods You override only the one you want to use

Fine if you want special events,but painful if you only want a click!

JButton b = new JButton(“Action!”);b.addMouseListener( new MouseAdapter() { // Only interested in clicks .. public void mouseClicked(MouseEvent e) { x = x + 1; }

} );

Page 63: Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there

What about the event parameter?

Look in the ..Event classes Properties of events eg Location

For those fancy drag-and-drop applications!

Now you can set the location of some other object ..And repaint …making the object follow the mouse, ...

JPanel p = new JPanel();p.addMouseListener( new MouseAdapter() { // Want to know where the mouse was pressed public void mousePressed(MouseEvent e) { x = e.getX(); y = e.getY(); … // Code to move something here repaint(); }

} );