Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Java Programming Introduction to Swing Class 7. Swing Graphical User Interface Provides Windows Menus Buttons Labels Textboxes In the beginning, there."— Presentation transcript:

1 Java Programming Introduction to Swing Class 7

2 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

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

4 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!

5 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

6 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

7 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

8 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

9 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

10 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

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

12 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

13 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

14 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

15 Those labels are boring... Changing them … Swing API Documentation cached at.. http://www.javasoft.com Observe the hierarchy Object Component Container JComponent JLabel

16 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

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

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

19 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

20 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

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

22 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

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

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

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

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

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

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

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

30 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

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

32 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

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

34 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

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

36 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

37 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

38 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

39 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

40 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

41 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

42 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!)

43 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

44 … 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

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

46 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!

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

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

49 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!

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

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

52 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

53 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

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

55 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

56 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!

57 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

58 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 { … }

59 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

60 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 { … }

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

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

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


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

Similar presentations


Ads by Google