2/17/2009
CS 335 Java Programming – GUI and Swing
Java: Basic GUI Components
Swing component overview Event handling Inner classes and anonymous inner classes Examples and various components Layouts Panels
1
2/17/2009
Alternatives
AWT (almost obsolete now) SWT (The Standard Widget Toolkit) – – –
Open source from IBM Using native window calls – fast response Very much like MFC
Swing Components
Lightweight vs. heavyweight components: – –
Lightweight: platform independent Heavyweight: tied to platform; windowing system
Swing components are lightweight
2
2/17/2009
Superclasses of Swing’s Lightweight GUI Components
Common lightweight component features – – – – –
Pluggable look-and-feel to customize the appearance of components Shortcut keys (called mnemonics) Common event-handling capabilities Brief description of component’s purpose (called tool tips) Support for localization 5
A Java Screen Layout
Frame JFrame Menu Bar (optional) Content Pane
3
2/17/2009
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class FrameDemo { public static void main(String s[]) { JFrame frame = new JFrame("FrameDemo"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); JLabel myLabel = new JLabel(“Hello World"); myLabel.setPreferredSize(new Dimension(175, 100)); frame.getContentPane().add(myLabel, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); // show() is “deprecated” } }
Choose Look and Feel
Only available under Swing
try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { } Always give me the java look! Ref: available look and feel at http://java.sun.com/docs/books/tutorial/uiswing/misc/plaf.html
4
2/17/2009
The Event Handing Model
GUI components are event-driven Programmer must – –
register events implement event handlers
Event registration: add “listeners” Event implementation: define listener methods
3 Steps for an Event Handler 1.
either implements a listener interface or extends a class that implements a listener interface public class MyClass implements ActionListener {
2.
Register your listener someComponent. addActionListener(instanceOfMyClass);
3.
Implement user action public void actionPerformed(ActionEvent e) { ...//code that reacts to the action... }
5
2/17/2009
Example: Registering Events public class TextFieldTest extends JFrame { private JTextField text1, text2, text3; private JPasswordField password; public TextFieldTest() { super( "Testing JTextField and JPasswordField" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); // construct textfield with default sizing text1 = new JTextField( 10 ); c.add( text1 ); // construct textfield with default text text2 = new JTextField( "Enter text here" ); c.add( text2 );
// construct textfield with default text and // 20 visible elements and no event handler text3 = new JTextField( "Uneditable text field", 20 ); text3.setEditable( false ); c.add( text3 ); // construct textfield with default text password = new JPasswordField( "Hidden text" ); c.add( password ); TextFieldHandler handler = new TextFieldHandler(); text1.addActionListener( handler ); text2.addActionListener( handler ); text3.addActionListener( handler ); password.addActionListener( handler ); setSize( 325, 100 ); show(); }
6
2/17/2009
Event Registration
Listeners for Event Types
ActionListener MouseListener MouseMotionListener KeyListener ButtonChangeListener AncestorListener PropertyChangeListener ...
7
2/17/2009
Example: Handling Events // inner class for event handling private class TextFieldHandler implements ActionListener { public void actionPerformed( ActionEvent e ) { String s = ""; if ( e.getSource() == text1 ) s = "text1: " + e.getActionCommand(); else if ( e.getSource() == text2 ) s = "text2: " + e.getActionCommand(); else if ( e.getSource() == text3 ) s = "text3: " + e.getActionCommand(); else if ( e.getSource() == password ) { JPasswordField pwd = (JPasswordField) e.getSource(); s = "password: " + new String( pwd.getPassword() ); } JOptionPane.showMessageDialog( null, s ); }
Driver for Example public static void main( String args[] ) { TextFieldTest app = new TextFieldTest(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); }
8
2/17/2009
Event Handling and Inner Classes
Event handler classes are usually private Often event handlers are anonymous inner classes defined purely to implement the handing method: app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } );
GUI Components http://java.sun.com/docs/books/tutorial/uiswing/components/components.html
For example JTextField and JPasswordField JButton JCheckBox and JRadioButton JComboBox JList and Multiple Selection Lists
9
2/17/2009
JTextField and JPasswordField
JButton
public class ButtonTest extends JFrame { private JButton plainButton, fancyButton; public ButtonTest() { super( "Testing Buttons" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); // create buttons plainButton = new JButton( "Plain Button" ); c.add( plainButton );
10
2/17/2009
Icon bug1 = new ImageIcon( "bug1.gif" ); Icon bug2 = new ImageIcon( "bug2.gif" ); fancyButton = new JButton( "Fancy Button", bug1 ); fancyButton.setRolloverIcon( bug2 ); c.add( fancyButton ); // create an instance of inner class ButtonHandler // to use for button event handling ButtonHandler handler = new ButtonHandler(); fancyButton.addActionListener( handler ); plainButton.addActionListener( handler ); setSize( 275, 100 ); show(); }
public static void main( String args[] ) { ButtonTest app = new ButtonTest(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); // or NEW for ver 1.3 of java 2 // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } // inner class for button event handling private class ButtonHandler implements ActionListener { public void actionPerformed( ActionEvent e ) { JOptionPane.showMessageDialog( null, "You pressed: " + e.getActionCommand() ); } } }
11
2/17/2009
Mouse Event Handling
Mouse events – –
– –
Create a MouseEvent object Handled by MouseListeners and MouseMotionListeners MouseInputListener combines the two interfaces Interface MouseWheelListener declares method mouseWheelMoved to handle MouseWheelEvents 23
Event Handling: The Mouse
mousePressed mouseClicked mouseReleased mouseEntered, mouseExited mouseDragged mouseMoved
12
2/17/2009
Note
Method calls to mouseDragged and mouseReleased are sent to the MouseMotionListener for the Component on which a mouse drag operation started. Similarly, the mouseReleased method call at the end of a drag operation is sent to the MouseListener for the Component on which the drag operation started.
// Fig. 12.17: MouseTracker.java // Demonstrating mouse events. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MouseTracker extends JFrame implements MouseListener, MouseMotionListener { private JLabel statusBar; public MouseTracker() { super( "Demonstrating Mouse Events" ); statusBar = new JLabel(); getContentPane().add( statusBar, BorderLayout.SOUTH ); // application listens to its own mouse events addMouseListener( this ); addMouseMotionListener( this ); setSize( 275, 100 ); show(); }
13
2/17/2009
// MouseListener event handlers public void mouseClicked( MouseEvent e ) { statusBar.setText( "Clicked at [" + e.getX() + ", " + e.getY() + "]" ); } public void mousePressed( MouseEvent e ) { statusBar.setText( "Pressed at [" + e.getX() + ", " + e.getY() + "]" ); } public void mouseReleased( MouseEvent e ) { statusBar.setText( "Released at [" + e.getX() + ", " + e.getY() + "]" ); } public void mouseEntered( MouseEvent e ) { statusBar.setText( "Mouse in window" ); } public void mouseExited( MouseEvent e ) { statusBar.setText( "Mouse outside window" ); }
// MouseMotionListener event handlers public void mouseDragged( MouseEvent e ) { statusBar.setText( "Dragged at [" + e.getX() + ", " + e.getY() + "]" ); } public void mouseMoved( MouseEvent e ) { statusBar.setText( "Moved at [" + e.getX() + ", " + e.getY() + "]" ); } public static void main( String args[] ) { MouseTracker app = new MouseTracker(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } }
14
2/17/2009
Adapter Classes
Interfaces with many methods to implement can be cumbersome The adapter class provides a default implementation of all interface methods Application can over-ride interface methods that are of interest
Adapter Classes
Adapter class – –
Implements event listener interface Provides default implementation for all eventhandling methods
30
15
2/17/2009
Software Engineering Observation 11.7
When a class implements an interface, the class has an “is a” relationship with that interface. All direct and indirect subclasses of that class inherit this interface. Thus, an object of a class that extends an eventadapter class is an object of the corresponding event-listener type (e.g., an object of a subclass of MouseAdapter is a MouseListener).
31
Extending MouseAdapter
MouseAdapter – –
Adapter class for MouseListener and MouseMotionListener interfaces Extending class allows you to override only the methods you wish to use
32
16
2/17/2009
Adapter Classes Event-adapter class in java.awt.event
Implements interface
ComponentAdapter ContainerAdapter FocusAdapter KeyAdapter MouseAdapter MouseMotionAdapter WindowAdapter
ComponentListener ContainerListener FocusListener KeyListener MouseListener MouseMotionListener WindowListener
// Fig. 12.19: Painter.java // Using class MouseMotionAdapter. import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Painter extends JFrame { private int xValue = -10, yValue = -10; public Painter() { super( "A simple paint program" ); getContentPane().add( new Label( "Drag the mouse to draw" ), BorderLayout.SOUTH ); addMouseMotionListener( new MouseMotionAdapter() { public void mouseDragged( MouseEvent e ) { xValue = e.getX(); Inner Class yValue = e.getY(); repaint(); } } ); setSize( 300, 150 ); show(); }
17
2/17/2009
public void paint( Graphics g ) { g.fillOval( xValue, yValue, 4, 4 ); } public static void main( String args[] ) { Painter app = new Painter(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } }
Using an Anonymous Inner Class for Event Handling
Anonymous inner class – – – –
Special form of inner class Declared without a name Typically appears inside a method call Has limited access to local variables
36
18
2/17/2009
Swing Component Demo
Try This http://java.sun.com/docs/books/tutorial/uiswin g/examples/components/index.html
19