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

Slides:



Advertisements
Similar presentations
Graphical User Interfaces (Part IV)
Advertisements

CS18000: Problem Solving and Object-Oriented Programming.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Fall 2007CS 225 Graphical User Interfaces Event Handling Appendix C.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
Java GUI Libraries Swing Programming. Swing Components Swing is a collection of libraries that contains primitive widgets or controls used for designing.
CS102--Object Oriented Programming Lecture 19: – The Swing Package (II) Copyright © 2008 Xiaoyan Li.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
CPSC150 Week 12 Graphical User Interfaces Chapter 11.
GUI Programming in Java Tim McKenna GUI Programming Concepts l conventional programming: sequence of operations is determined by the program.
Graphic User Interfaces Part 1. Typical GUI Screen from Microsoft Word What GUI “components” can you see? –Menus? Buttons? Labels? What else? –Anything.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
GUI Programming in Java
Java Programming Chapter 10 Graphical User Interfaces.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
עקרונות תכנות מונחה עצמים תרגול 4 - GUI. Outline  Introduction to GUI  Swing  Basic components  Event handling.
Java GUI building with Swing. 2 AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
CS Lecture 01 Frames and Components and events Lynda Thomas
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
SWING. AbstractButton Swing Buttons are subclasses of the AbstractButton class, which extends JComponent. Abstract class javax.swing.AbstractButton AbstractButton.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
GUI Clients 1 Enterprise Applications CE00465-M Clients with Graphical User Interfaces.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
OOP (Java): GUI Intro/ OOP Objectives – –use an image viewer application to introduce Java's GUI features Semester 2,
Java Programming Applets. Topics Write an HTML document to host an applet Understand simple applets Use Labels with simple AWT applets Write a simple.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
CS1054: Lecture 21 - Graphical User Interface. Graphical User Interfaces vs. Text User Interface.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
Basics of GUI Programming Chapter 11 and Chapter 22.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Java Swing One of the most important features of Java is its ability to draw graphics.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
Computer Science [3] Java Programming II - Laboratory Course Lab 4 -1 : Introduction to Graphical user interface GUI Components Faculty of Engineering.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 17.1 Test-Driving the Student Grades Application.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Lesson 28: More on the GUI button, frame and actions.
Graphical User Interface (GUI)
1 Lecture 8: User Interface Components with Swing.
Applets. 9/04/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L12: Applets Slide 2 Applets Usually.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
Chapter 6 Building Java GUIs. MVC Model View Controller The model passes its data to the view for rendering The view determines which events are passed.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
Graphical User Interfaces
A First Look at GUI Applications
Ellen Walker Hiram College
Course Outcomes of Advanced Java Programming AJP (17625, C603)
Steps to Creating a GUI Interface
Constructors, GUI’s(Using Swing) and ActionListner
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

Java Programming Introduction to Swing Class 7

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

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); }

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); } import java.awt.*; import javax.swing.*; Import classes from java.awt javax.swing packages The * implies import all classes in the package You could import some parts of a package, but few seem to be keen to type out lists of names! Swing is built on java.awt You can mix them … Not recommended though!

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 enables this class to run as a stand-alone application

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 final You can’t change the value Each object acquires an instance of other variables declared in this area! static There’s only one instance of this variable for the whole class

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 prefix for Swing classes ( awt has Label ) Construct an instance of the array with n_label elements

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 JWindow a stand-alone window Initialise it immediately by calling the JWindow constructor with new

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 itself You must get one of its content panes (it has three) and draw in that! The panes are Container s You can add things to them Here we apply the getContentPane() method to the window to return its content pane

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

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 components in a Container is determined by a Layout Manager BorderLayout() - one of the layout managers More soon..

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

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 it to its string representation + Creates a string by concatenating its arguments

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 the minimum size window Finished, so exit Show the window

Those labels are boring... Changing them … Swing API Documentation cached at.. Observe the hierarchy Object Component Container JComponent JLabel

Those labels are boring... Changing them … Note the specification public class JLabel extends JComponent implements SwingConstants, Accessible JComponent is the immediate ‘ancestor’ or superclass JLabel provides the methods in these interfaces

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();

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

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

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 typename number of arguments types of arguments

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 horAlogin JLabel( String text, int horAlign );

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

Other common components Buttons JCheckBox Checked box.. Selected / Not selected It’s a specialization of JToggleButton ! JRadioButton Similar to JCheckBox

Frames & Applets JFrame Specialization of Frame Adds Border Menubar Close box JApplet Similar to JFrame Both have ContentPane GlassPane

Panels JPanel Useful as a container for other elements Window, Frame or Applet Panel2Panel1 Button in Panel1 Button in Panel2

Panels JPanel Useful as a container for other elements Panel2Panel1 Button in Panel1 Button in 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 );

Panels JPanel Make the panels classes! Panel2Panel1 Button in Panel1 Button in 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); }

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

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

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

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

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 w to add the label to it Use the getC..C.. Method to find out how many components the window has Diagnostics: You will need this System method!! Show the window

Java Programming Swing (continued) 10 mins break (not more)

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

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

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

Making a Listener - Method 1 Define a class implementing ActionListener 1 // Event Handler import 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 parent parent = m; } // ActionListener interface public 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’s only one.. actionPerformed

Making a Listener - Method 1 Define a class implementing ActionListener // Event Handler import 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 parent parent = m; } // ActionListener interface public 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 method must be identical to the specification! All must match Name Return type Parameter List

Making a Listener - Method 1 Define a class implementing ActionListener // Event Handler import 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 parent parent = m; } // ActionListener interface public void actionPerformed( ActionEvent e ) { System.out.println("aP event " + e ); src = (JComponent)(e.getSource()); } } The constructor may be used 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

Making a Listener - Method 1 Define a class implementing ActionListener // Event Handler import 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 parent parent = m; } // ActionListener interface public void actionPerformed( ActionEvent e ) { System.out.println("aP event " + e ); src = (JComponent)(e.getSource()); } } The constructor may be used 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

Making a Listener - Method 1 Define a class implementing ActionListener // Event Handler import 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 parent parent = m; } // ActionListener interface public void actionPerformed( ActionEvent e ) { System.out.println("aP event " + e ); src = (JComponent)(e.getSource()); } } The interface method will be called whenever the appropriate event is fired by a component to which a listener has been attached

Making a Listener - Method 1 Define a class implementing ActionListener // Event Handler import 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 parent parent = m; } // ActionListener interface public 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!)

Making a Listener - Method 1 Define a class implementing ActionListener // Event Handler import 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 parent parent = m; } // ActionListener interface public 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

… 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 forget to get the content pane! Construct a JButton Instantiate an event handler Add the button to the window Attach the event handler to the button

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 ); }

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!

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 ); }

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; } }

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!

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 // depending on whether this is obj }

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 handler can access attributes of its object (just like any other method)

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 just like any other class

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 access attributes of the enclosing class

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 ); …… }

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

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 argument should be an ActionListener object So create one “on-the-fly” here You don’t need to give this class a name.. Hence it’s anonymous!

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 object by calling its constructor preceded by new It’s an ActionListener - just put the name of the interface here

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 any arguments but don’t forget the ( ) Normal class body in { … }

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 provide actionPerformed.. and we can still access attributes of the enclosing class

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 object by calling its constructor preceded by new The constructor doesn’t have any arguments but don’t forget the ( ) Normal class body in { … }

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) { … } } );

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; } } );

What about the event parameter? Look in the..Event classes 1 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(); } } );