CS 335 Lecture 06
Java Programming – GUI and Swing
Java: Basic GUI Components
z Swing component overview
z Event handling
z Inner classes and anonymous inner classes
z Examples and various components
z Layouts
z Panels
Alternatives
z AWT (almost obsolete now)
z SWT (The Standard Widget Toolkit)
– Open source from IBM
– Using native window calls – fast response
– Very much like MFC
Swing Components
z 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
z 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
z 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
z GUI components are event-driven
z Programmer must
– register events
– implement event handlers
z Event registration: add “listeners”
z 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
z ActionListener
z MouseListener
z MouseMotionListener
z KeyListener
z ButtonChangeListener
z AncestorListener
z PropertyChangeListener
z ...
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
z Event handler classes are usually private
z 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
z JTextField and JPasswordField
z JButton
z JCheckBox and JRadioButton
z JComboBox
z 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
z mousePressed
z mouseClicked
z mouseReleased
z mouseEntered, mouseExited
z mouseDragged
z 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
z Interfaces with many methods to implement
can be cumbersome
z The adapter class provides a default
implementation of all interface methods
z 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 );
} } );
} }