Sie sind auf Seite 1von 28

CS 335 Lecture 07 Java Programming GUI and Swing

Fall 2003

Java: Basic GUI Components


Swing component overview Event handling Inner classes and anonymous inner classes Examples and various components Layouts Panels

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.*; import java.awt.event.*; import java.awt.event.*; import javax.swing.*; import javax.swing.*; public class FrameDemo { public class FrameDemo { public static void main(String s[]) { public static void main(String s[]) { JFrame frame = new JFrame("FrameDemo"); JFrame frame = new JFrame("FrameDemo"); frame.addWindowListener(new WindowAdapter() { frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { public void windowClosing(WindowEvent e) { System.exit(0); System.exit(0); } } }); }); JLabel myLabel = new JLabel(Hello World"); JLabel myLabel = new JLabel(Hello World"); myLabel.setPreferredSize(new Dimension(175, 100)); myLabel.setPreferredSize(new Dimension(175, 100)); frame.getContentPane().add(myLabel, frame.getContentPane().add(myLabel, BorderLayout.CENTER); BorderLayout.CENTER); frame.pack(); frame.pack(); frame.setVisible(true); // show() is deprecated frame.setVisible(true); // show() is deprecated

} }

} }

Choose Look and Feel


Only available under Swing
try { try {

UIManager.setLookAndFeel( UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { } } 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 { public class TextFieldTest extends JFrame { private JTextField text1, text2, text3; private JTextField text1, text2, text3; private JPasswordField password; private JPasswordField password; public TextFieldTest() public TextFieldTest() { { super( "Testing JTextField and JPasswordField" ); super( "Testing JTextField and JPasswordField" ); Container c = getContentPane(); Container c = getContentPane(); c.setLayout( new FlowLayout() ); c.setLayout( new FlowLayout() ); // construct textfield with default sizing // construct textfield with default sizing text1 = new JTextField( 10 ); text1 = new JTextField( 10 ); c.add( text1 ); c.add( text1 ); // construct textfield with default text // construct textfield with default text text2 = new JTextField( "Enter text here" ); text2 = new JTextField( "Enter text here" ); c.add( text2 ); c.add( text2 );

// construct textfield with default text and // construct textfield with default text and // 20 visible elements and no event handler // 20 visible elements and no event handler text3 = new JTextField( "Uneditable text field", 20 ); text3 = new JTextField( "Uneditable text field", 20 ); text3.setEditable( false ); text3.setEditable( false ); c.add( text3 ); c.add( text3 ); // construct textfield with default text // construct textfield with default text password = new JPasswordField( "Hidden text" ); password = new JPasswordField( "Hidden text" ); c.add( password ); c.add( password ); TextFieldHandler handler = new TextFieldHandler(); TextFieldHandler handler = new TextFieldHandler(); text1.addActionListener( handler ); text1.addActionListener( handler ); text2.addActionListener( handler ); text2.addActionListener( handler ); text3.addActionListener( handler ); text3.addActionListener( handler ); password.addActionListener( handler ); password.addActionListener( handler ); setSize( 325, 100 ); setSize( 325, 100 ); show(); show();

} }

Event Registration

Listeners for Event Types


ActionListener MouseListener MouseMotionListener KeyListener ButtonChangeListener AncestorListener PropertyChangeListener ...

Example: Handling Events


// inner class for event handling // inner class for event handling private class TextFieldHandler implements ActionListener { private class TextFieldHandler implements ActionListener { public void actionPerformed( ActionEvent e ) public void actionPerformed( ActionEvent e ) { { String s = ""; String s = ""; if ( e.getSource() == text1 ) if ( e.getSource() == text1 ) s = "text1: " + e.getActionCommand(); s = "text1: " + e.getActionCommand(); else if ( e.getSource() == text2 ) else if ( e.getSource() == text2 ) s = "text2: " + e.getActionCommand(); s = "text2: " + e.getActionCommand(); else if ( e.getSource() == text3 ) else if ( e.getSource() == text3 ) s = "text3: " + e.getActionCommand(); s = "text3: " + e.getActionCommand(); else if ( e.getSource() == password ) { else if ( e.getSource() == password ) { JPasswordField pwd = JPasswordField pwd = (JPasswordField) e.getSource(); (JPasswordField) e.getSource(); s = "password: " + s = "password: " + new String( pwd.getPassword() ); new String( pwd.getPassword() ); } } } } JOptionPane.showMessageDialog( null, s ); JOptionPane.showMessageDialog( null, s );

Driver for Example


public static void main( String args[] ) public static void main( String args[] ) { { TextFieldTest app = new TextFieldTest(); TextFieldTest app = new TextFieldTest(); app.addWindowListener( app.addWindowListener( new WindowAdapter() { new WindowAdapter() { public void windowClosing( WindowEvent e ) public void windowClosing( WindowEvent e ) { { System.exit( 0 ); 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( app.addWindowListener( new WindowAdapter() { new WindowAdapter() { public void windowClosing( WindowEvent e ) public void windowClosing( WindowEvent e ) { { System.exit( 0 ); 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 { public class ButtonTest extends JFrame { private JButton plainButton, fancyButton; private JButton plainButton, fancyButton; public ButtonTest() public ButtonTest() { { super( "Testing Buttons" ); super( "Testing Buttons" ); Container c = getContentPane(); Container c = getContentPane(); c.setLayout( new FlowLayout() ); c.setLayout( new FlowLayout() ); // create buttons // create buttons plainButton = new JButton( "Plain Button" ); plainButton = new JButton( "Plain Button" ); c.add( plainButton ); c.add( plainButton );

Icon bug1 = new ImageIcon( "bug1.gif" ); Icon bug1 = new ImageIcon( "bug1.gif" ); Icon bug2 = new ImageIcon( "bug2.gif" ); Icon bug2 = new ImageIcon( "bug2.gif" ); fancyButton = new JButton( "Fancy Button", bug1 ); fancyButton = new JButton( "Fancy Button", bug1 ); fancyButton.setRolloverIcon( bug2 ); fancyButton.setRolloverIcon( bug2 ); c.add( fancyButton ); c.add( fancyButton ); // create an instance of inner class ButtonHandler // create an instance of inner class ButtonHandler // to use for button event handling // to use for button event handling ButtonHandler handler = new ButtonHandler(); ButtonHandler handler = new ButtonHandler(); fancyButton.addActionListener( handler ); fancyButton.addActionListener( handler ); plainButton.addActionListener( handler ); plainButton.addActionListener( handler ); setSize( 275, 100 ); setSize( 275, 100 ); show(); show();

} }

public static void main( String args[] ) public static void main( String args[] ) { { ButtonTest app = new ButtonTest(); ButtonTest app = new ButtonTest(); app.addWindowListener( app.addWindowListener( new WindowAdapter() { new WindowAdapter() { public void windowClosing( WindowEvent e ) public void windowClosing( WindowEvent e ) { System.exit( 0 ); } { System.exit( 0 ); } } } ); ); // or NEW for ver 1.3 of java 2 // or NEW for ver 1.3 of java 2 // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } // inner class for button event handling // inner class for button event handling private class ButtonHandler implements ActionListener { private class ButtonHandler implements ActionListener { public void actionPerformed( ActionEvent e ) public void actionPerformed( ActionEvent e ) { { JOptionPane.showMessageDialog( null, JOptionPane.showMessageDialog( null, "You pressed: " + e.getActionCommand() ); "You pressed: " + e.getActionCommand() ); } } } }

} }

Event Handling: The Mouse


mousePressed mouseClicked mouseReleased mouseEntered, mouseExited mouseDragged mouseMoved

// Fig. 12.17: MouseTracker.java // Fig. 12.17: MouseTracker.java // Demonstrating mouse events. // Demonstrating mouse events. import java.awt.*; import java.awt.*; import java.awt.event.*; import java.awt.event.*; import javax.swing.*; import javax.swing.*; public class MouseTracker extends JFrame public class MouseTracker extends JFrame implements MouseListener, MouseMotionListener { implements MouseListener, MouseMotionListener { private JLabel statusBar; private JLabel statusBar; public MouseTracker() public MouseTracker() { { super( "Demonstrating Mouse Events" ); super( "Demonstrating Mouse Events" ); statusBar = new JLabel(); statusBar = new JLabel(); getContentPane().add( statusBar, BorderLayout.SOUTH ); getContentPane().add( statusBar, BorderLayout.SOUTH ); // application listens to its own mouse events // application listens to its own mouse events addMouseListener( this ); addMouseListener( this ); addMouseMotionListener( this ); addMouseMotionListener( this ); setSize( 275, 100 ); setSize( 275, 100 ); show(); show();

} }

// MouseListener event handlers // MouseListener event handlers public void mouseClicked( MouseEvent e ) public void mouseClicked( MouseEvent e ) { { statusBar.setText( "Clicked at [" + e.getX() + statusBar.setText( "Clicked at [" + e.getX() + ", " + e.getY() + "]" ); ", " + e.getY() + "]" ); } } public void mousePressed( MouseEvent e ) public void mousePressed( MouseEvent e ) { { statusBar.setText( "Pressed at [" + e.getX() + statusBar.setText( "Pressed at [" + e.getX() + ", " + e.getY() + "]" ); ", " + e.getY() + "]" ); } } public void mouseReleased( MouseEvent e ) public void mouseReleased( MouseEvent e ) { { statusBar.setText( "Released at [" + e.getX() + statusBar.setText( "Released at [" + e.getX() + ", " + e.getY() + "]" ); ", " + e.getY() + "]" ); } } public void mouseEntered( MouseEvent e ) public void mouseEntered( MouseEvent e ) { { statusBar.setText( "Mouse in window" ); statusBar.setText( "Mouse in window" ); } } public void mouseExited( MouseEvent e ) public void mouseExited( MouseEvent e ) { { statusBar.setText( "Mouse outside window" ); statusBar.setText( "Mouse outside window" ); } }

// MouseMotionListener event handlers // MouseMotionListener event handlers public void mouseDragged( MouseEvent e ) public void mouseDragged( MouseEvent e ) { { statusBar.setText( "Dragged at [" + e.getX() + statusBar.setText( "Dragged at [" + e.getX() + ", " + e.getY() + "]" ); ", " + e.getY() + "]" ); } } public void mouseMoved( MouseEvent e ) public void mouseMoved( MouseEvent e ) { { statusBar.setText( "Moved at [" + e.getX() + statusBar.setText( "Moved at [" + e.getX() + ", " + e.getY() + "]" ); ", " + e.getY() + "]" ); } } public static void main( String args[] ) public static void main( String args[] ) { { MouseTracker app = new MouseTracker(); MouseTracker app = new MouseTracker(); app.addWindowListener( app.addWindowListener( new WindowAdapter() { new WindowAdapter() { public void windowClosing( WindowEvent e ) public void windowClosing( WindowEvent e ) { { System.exit( 0 ); 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 // Fig. 12.19: Painter.java // Using class MouseMotionAdapter. // Using class MouseMotionAdapter. import javax.swing.*; import javax.swing.*; import java.awt.event.*; import java.awt.event.*; import java.awt.*; import java.awt.*; public class Painter extends JFrame { public class Painter extends JFrame { private int xValue = -10, yValue = -10; private int xValue = -10, yValue = -10; public Painter() public Painter() { { super( "A simple paint program" ); super( "A simple paint program" ); getContentPane().add( getContentPane().add( new Label( "Drag the mouse to draw" ), new Label( "Drag the mouse to draw" ), BorderLayout.SOUTH ); BorderLayout.SOUTH ); addMouseMotionListener( addMouseMotionListener( new MouseMotionAdapter() { new MouseMotionAdapter() { public void mouseDragged( MouseEvent e ) public void mouseDragged( MouseEvent e ) { { xValue = e.getX(); xValue = e.getX(); Inner Class yValue = e.getY(); yValue = e.getY(); repaint(); repaint(); } } } } ); ); setSize( 300, 150 ); setSize( 300, 150 ); show(); show();

} }

public void paint( Graphics g ) public void paint( Graphics g ) { { g.fillOval( xValue, yValue, 4, 4 ); g.fillOval( xValue, yValue, 4, 4 ); } } public static void main( String args[] ) public static void main( String args[] ) { { Painter app = new Painter(); Painter app = new Painter(); app.addWindowListener( app.addWindowListener( new WindowAdapter() { new WindowAdapter() { public void windowClosing( WindowEvent e ) public void windowClosing( WindowEvent e ) { { System.exit( 0 ); System.exit( 0 ); } } } } ); );

} }

} }

Das könnte Ihnen auch gefallen