CS 335 Lecture 06 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
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 Peer object: object responsible for interactions between heavyweight object and local system Swing components are lightweight
A Java Screen Layout Frame JFrame Menu Bar (optional) Content Pane
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
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...
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();
Event Registration
Listeners for Event Types ActionListener MouseListener MouseMotionListener KeyListener ButtonChangeListener AncestorListener PropertyChangeListener...
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 ); );
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
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 );
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() );
Event Handling: The Mouse mousepressed mouseclicked mousereleased mouseentered, mouseexited mousedragged mousemoved
// 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();
// 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 ); );
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
// 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(); yvalue = e.gety(); repaint(); ); setsize( 300, 150 ); show(); Inner Class
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 ); );