• No results found

CS 335 Lecture 06 Java Programming GUI and Swing

N/A
N/A
Protected

Academic year: 2021

Share "CS 335 Lecture 06 Java Programming GUI and Swing"

Copied!
29
0
0

Loading.... (view fulltext now)

Full text

(1)

CS 335 Lecture 06

Java Programming – GUI and Swing

(2)

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

(3)

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

(4)

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

(5)

A Java Screen Layout

Frame Æ JFrame

Menu Bar (optional)

Content Pane

(6)

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”

} }

(7)

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

(8)

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

(9)

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

(10)

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

(11)

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

}

(12)

Event Registration

(13)

Listeners for Event Types

z ActionListener

z MouseListener

z MouseMotionListener

z KeyListener

z ButtonChangeListener

z AncestorListener

z PropertyChangeListener

z ...

(14)

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

}

(15)

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

}

}

);

}

(16)

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

}

}

);

(17)

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

(18)

JTextField and JPasswordField

(19)

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

(20)

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

}

(21)

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

} } }

(22)

Event Handling: The Mouse

z mousePressed

z mouseClicked

z mouseReleased

z mouseEntered, mouseExited

z mouseDragged

z mouseMoved

(23)

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

}

(24)

// 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" );

}

(25)

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

} } );

} }

(26)

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

(27)
(28)

// 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

(29)

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

} } );

} }

References

Related documents

public class XorSocket extends Socket { private final byte pattern;}. private InputStream in

public class CurrencyConverter extends JFrame implements ActionListener { final Currency EUR = new Currency("EUR", 1.0);. JComboBox

To respond to this event, this JFrame class must implement the ActionListener interface and define an actionPerformed() method, as shown here:.. public class MyGUIController

emphasized that at least in the field of the self-employment share, East Germany has successfully caught-up: start-up activities in East Germany exceeded those in West- Germany

The objective of this work was to review disasters that have happened in Kenya in the last twenty five years in respect to their public health impact, community perceptions and

Instead, we describe a practi- cal method for incorporating the value of learning in sponsored search auctions, and analyze its revenue and efficiency impacts through simulations

Root canal preparation was performed in all teeth by means of the Reciproc system (VDW, Germany). Mesial and buccal canals were enlarged up to R25, while palatal and distal

Hence, in practice, the usual approach is to determine the VTTS of the project under evaluation according to recommended values at a national level (see for example UNITE