CompSci 230 S2 2015 Software Construction Applets & AWT.

31
CompSci 230 S2 2015 Software Construction Applets & AWT

Transcript of CompSci 230 S2 2015 Software Construction Applets & AWT.

Page 1: CompSci 230 S2 2015 Software Construction Applets & AWT.

CompSci 230 S2 2015Software Construction

Applets & AWT

Page 2: CompSci 230 S2 2015 Software Construction Applets & AWT.

Agenda Applets Abstract Windowing Toolkit (AWT)

Basic AWT windows Basic AWT user interface controls Button, checkbox, radio button, list box, scrollbars Processing events in GUI controls

Reading: Getting Started with Graphics

https://docs.oracle.com/javase/tutorial/2d/basic2d/ Java AWT Tutorial

22 112

Page 3: CompSci 230 S2 2015 Software Construction Applets & AWT.

Java Applets: a simple GUI framework

Applet framework (web browser)

Application code

init( )

start( )

paint( ) stop( )

destroy( )

Applet

init( )start( )paint( )stop( )destroy( )

Examples: C:\Program Files\Java\jdk1.8.0_45\demo\applets

113

Page 4: CompSci 230 S2 2015 Software Construction Applets & AWT.

Applet Class Applet defines a set of so-called lifecycle methods

that are expected to be implemented by sucbclasses. init( ) –

executed when the web browser loads the Applet subclass code. This method is often implemented to acquire resources – threads, sockets etc.

start( ) – executed when the applet should start its execution.

paint( ) – called whenever the applet is to paint itself, (e.g. a person has moved

on the tic-tac-toe game) has changed. Typically called multiple times. stop( ) –

called when the user leaves the web page that contains the applet. destroy( ) –

called by the browser on exit. This gives the applet the chance to clean up – e.g. close sockets.

114

Page 5: CompSci 230 S2 2015 Software Construction Applets & AWT.

Example: Blink

public class Blink extends java.applet.Applet {

...

public void init() {

...

public void start() {

...

public void paint(Graphics g) {

...

public void stop() {

...

115

Page 6: CompSci 230 S2 2015 Software Construction Applets & AWT.

Example: Simple Simple.java Simple.html

Command: appletviewer Simple.html

...<body><applet code=Simple.class width=460 height=160></applet>

public class Simple extends Applet {

StringBuffer buffer;

public void init() { ...

Example: Simple.java

116

Page 7: CompSci 230 S2 2015 Software Construction Applets & AWT.

Abstract Windowing Toolkit Java’s AWT is a simple framework for developing

graphical user interfaces (GUIs) Key AWT packages include:

java.awt Contains core GUI component classes

Components are also known as widgets and may be “simple” (e.g. buttons, textfields) or “composite” (e.g. windows, frames, panels)

Includes layout managers that layout composite components’ children

java.awt.event Contains classes representing GUI events

Events represent things like window closing and restoration, button presses, mouse movement, keystrokes, etc. Components generate events

Provides listener interfaces Listener interfaces are provided that are intended to be implemented by

application developers; listener objects can be notified of events

7 117

Page 8: CompSci 230 S2 2015 Software Construction Applets & AWT.

A Component is something that can be displayed on a GUI and with which a user can interact.

A Window is a special Container that can be stacked, and moved to the front/back.

A Frame is a special Window with a title, menubar, and border.

Component is an abstract class.

Generalisation

Specialisation

A Container is a special component that can nest other components, be they simple components (e.g. Buttons, Labels) or themselves Containers (e.g. Panels).

add( ) is a polymorphic method; it can take as actual argument any kind of Component.

Nothing in this class hierarchy is application specific. These classes provide a reusable resource that is extended to meet the needs of any particular application.

118

Page 9: CompSci 230 S2 2015 Software Construction Applets & AWT.

AWT framework Component

an abstract class superclass of all GUI components except menu components and class

CheckboxGroup repaint() schedules Component instance for repainting. The AWT

framework will subsequently call paint( ) on the Component Container

the superclass for all components that contain other components defines add(), for adding components to a container

Component

Container

Object

ButtonLabel Many other classes

getSize( ) : intsetSize( width : int, height : int ) : voidsetVisible( visible : boolean ) : voidrepaint( g : Graphics ) : voidpaint( g : Graphics ) : voidaddMouseListener( listener : MouseListener ) : voidaddKeyListener( listener : KeyListener ) : void

setLayout( mgr : LayoutManager ) : voidadd( c : Component ) : void

119

Page 10: CompSci 230 S2 2015 Software Construction Applets & AWT.

AWT framework Window

a top-level window with no border or menu bar rarely instantiated (its subclasses are more useful)

Frame a window with a title bar can have a menu bar top-level window for Java AWT-based applications typically, main() creates an instance of Frame as its top-

level application window, then adds GUI components to the frame

default layout manager: BorderLayout

Window

Frame

Container

Dialog Many other classes

setTitle( title : String ) : voidsetCursor( c : int ) : voidsetResizable( resizable : boolean ) : voidsetMenuBar( mb : MenuBar ) : void 1110

Page 11: CompSci 230 S2 2015 Software Construction Applets & AWT.

Frame class Creating and Using – Two Approaches:

A fixed-size Frame: Use setSize() and setVisible(true) – for display

A Frame that stretches to fit what it contains pack(), and setVisible(true)

public class SimpleFixedFrame extends Frame { public SimpleFixedFrame(String title) { super(title); setSize(400, 300); setVisible(true); }}

public class StretchFrame extends Frame { public StretchFrame(String title) { super(title); add(new Button("hello"),BorderLayout.CENTER); pack(); setVisible(true); ...

Causes this Window to be sized to fit the preferred size and layouts of its

subcomponents

Example: SimpleFixedFrame.javaStretchFrame.java

1111

Page 12: CompSci 230 S2 2015 Software Construction Applets & AWT.

COMPSCI 230 Software Design & Construction 12

FramePanel

LabelTextField

Label

Panel

Button

Button

Panel

Component

Container

add( c : Component ) : void

class Container extends Component { private List<Component> children; … public void add( Component c ) { children.add( c ); }}

Frame instance

TextField instance

Panel instance

Buttoninstance

Buttoninstance

Labelinstance

Panel instance

Panel instance

Labelinstance

*

1112

Page 13: CompSci 230 S2 2015 Software Construction Applets & AWT.

PalindromeGUI Implementation

import java.awt.*;

public class PalindromeGUI extends Frame {

public PalindromeGUI( ) { super( "Palindrome detector" ); setUp( ); setLayout(new FlowLayout());

// Method inherited from class Window – // causes this object to be sized according // to its preferred size, based on its // children components. pack( );

setVisible( true ); }

public static void main( String[ ] args ) { PalindromeGUI = new PalindromeGUI( ); }

// “Helper” method to create components. private void setUp() { // Create intermediate panels. Panel inputPanel = new Panel( ); Panel outputPanel = new Panel( ); Panel buttonPanel = new Panel( );

// Create simple components. Label prompt = new Label( "Word/phrase" ); TextField text = new TextField( 20 ); Label output = new Label( "Please enter a word/phrase" ); Button isPalindrome = new Button( "Is palindrome" ); Button quit = new Button( "quit" );

// Add components to intermediate panels. inputPanel.add( prompt ); inputPanel.add( text ); outputPanel.add( output ); buttonPanel.add( isPalindrome ); buttonPanel.add( quit );

// Add panels to this object. add( inputPanel ); add( outputPanel ); add( buttonPanel ); }}

Example: PalindromeGUI.java

1113

Page 14: CompSci 230 S2 2015 Software Construction Applets & AWT.

Traversing the nested structure

14

Frame instance

TextField instance

Panel instance

Buttoninstance

Buttoninstance

Labelinstance

Panel instance

Panel instance

Labelinstance

class Container extends Component { private List<Component> children; … public void add( Component c ) { children.add( c ); }

public void paint( Graphics g ) { for( Component c : children ) c.paint( ); }}

1: paint( )

2: paint( )

3: paint( ) 4: paint( )

5

6

7

8

9

1114

Page 15: CompSci 230 S2 2015 Software Construction Applets & AWT.

Layout management Aggregation

15

Container

setLayout( mgr : LayoutManager ) : voiddoLayout( )add( c : Component ) : void

Component

<< interface >>LayoutManager

layoutContainer( c : Container )minimumLayoutSize( c : Container ) : DimensionpreferredLayoutSize( c : Container ) : Dimension

BorderLayout BoxLayout GridLayout FlowLayout

*

1

1115

Page 16: CompSci 230 S2 2015 Software Construction Applets & AWT.

button1 = new Button("Button 1 (PAGE_START)");add(button1, BorderLayout.PAGE_START);

button2 = new Button("Button 2 (CENTER)");button2.setPreferredSize(new Dimension(200, 100));add(button2, BorderLayout.CENTER);

button3 = new Button("Button 3 (LINE_START)");add(button3, BorderLayout.LINE_START);

button4 = new Button("Long-Named Button 4 (PAGE_END)");add(button4, BorderLayout.PAGE_END);

button5 = new Button("5 (LINE_END)");add(button5, BorderLayout.LINE_END);

Layout Managers FlowLayout:

Simplest, just one row BorderLayout:

This scheme defines five areas for the component. All extra space is placed in the center area.

BoxLayout, GridLayout, …

1116

Page 17: CompSci 230 S2 2015 Software Construction Applets & AWT.

Layout management

17

public class Container extends Component { … private List< Component > children; private LayoutManager ;

public void setLayout( LayoutManager lm ) { layoutManager = lm; }

public void doLayout( ) { layoutManager.layout( this ); }}

Frame instance

TextField instance

Panel instance

Buttoninstance

Buttoninstance

Labelinstance

Panel instance

Panel instance

Labelinstance

1: doLayout( )

2: layoutContainer( this )

LayoutManager instance

1117

Page 18: CompSci 230 S2 2015 Software Construction Applets & AWT.

Painting Class Component implements a

painting mechanism as follows: repaint( ) schedules the

component to be painted and should not be overriden

paint( ) is intended to be implemented by subclasses to perform subclass-specific painting E.g. A Button will paint itself as a

button, a Panel will call paint on each child, etc. AWT Framework code

Application code

Framework detects that a window has moved from the minimised to restored state. It calls repaint( ) on the window component

Framework calls paint( ) on the window component

Framework calls paint( ) on component C

AWT Framework code

Application code

Component

paint( g : Graphics )repaint( )

Framework triggers an event to which the application responds

Application makes a repaint( ) request for a particular component, C 1118

Page 19: CompSci 230 S2 2015 Software Construction Applets & AWT.

Painting: System-triggered A GUI component is displayed by "painting" it on screen. System-triggered painting

When? When the component is first shown When the component has been covered and uncovered

This causes the component's paint() method to be called You should place the component's rendering code inside a the paint

method When AWT invokes this method, the Graphics object parameter is

pre-configured with the appropriate state for drawing on this particular component E.g. color => component’s foreground propertypublic void paint(Graphics g) {

Dimension size = getSize(); int d = Math.min(size.width, size.height); // diameter int ed = d/20; // eye diameter int x = (size.width - d)/2; int y = (size.height - d)/2; g.fillOval(x, y, d, d); g.setColor(Color.black); g.drawOval(x, y, d, d); g.fillOval(x+d/3-(ed/2), y+d/3-(ed/2), ed, ed); g.fillOval(x+(2*(d/3))-(ed/2), y+d/3-(ed/2), ed, ed); g.drawArc(x+d/4, y+2*(d/5), d/2, d/3, 0, -180);}

Example: PaintDemo.java

1119

Page 20: CompSci 230 S2 2015 Software Construction Applets & AWT.

Painting: Application-triggered Application-triggered painting

The program’s Java code determines that a component should be repainted when you change text, colors, … In your own program, when you want to repaint

It calls repaint(), which queues a paint request You never call paint() directly! You always call repaint()!

The event handler thread calls the component's paint() method

MouseListener l = new MouseAdapter() { public void mousePressed(MouseEvent e) { MyButton b = (MyButton)e.getSource(); b.setSelected(true); b.repaint(); }};

1120

Page 21: CompSci 230 S2 2015 Software Construction Applets & AWT.

Event handling Components generate

events in response to user interaction

To hook in application-specific responses to events, listeners are used A listener is an object

that is registered with a component; in handling user interaction the component informs any registered listeners of events

AWT Framework code

Application code

Framework detects a button press and generates an event

Framework waits for next user interaction

Framework detects a mouse drag and generates an event

Registered listeners execute

Button instance Listener instance

event

1121

Page 22: CompSci 230 S2 2015 Software Construction Applets & AWT.

Event handling

<< interface >>ActionListener

actionPerformed( e : ActionEvent ) : void

<< interface >>KeyListener

keyPressed( e : KeyEvent ) : voidkeyReleased( e : KeyEvent ) : voidkeyTyped( e : KeyEvent ) : void

<< interface >>MouseListener

mouseReleased( e : MouseEvent ) : voidmouseClicked( e : MouseEvent ) : voidmouseEntered( e : MouseEvent ) : voidmouseExited( e : MouseEvent ) : void

AWT framework

Interface for receiving ActionEvents on a component

Interface for receiving key stroke events on a component

Interface for receiving mouse events (e.g. release, click, enter and exit) on a component

Button

addActionListener( listener : ActionListener )

ApplicationListener

Application

See API documentation for package java.awt.event for other listener interfaces

Button instance appListener : ApplicationListene

r

1: addActionListener( appListener )

2: actionPerformed( )

1122

Page 23: CompSci 230 S2 2015 Software Construction Applets & AWT.

Event Handling Event-driven programming is a programming

style that uses a signal-and-response approach to programming The sending of an event is called firing the event

The program itself no longer determines the order in which things can happen Instead, the events determine the order Typically, you do NOT call these event handlers

yourself Inversion of Control (IOC): Don't call us, we'll call you

Note: If you do want to capture events but forget to add a listener, no events will be captured (a common omission). 1123

Page 24: CompSci 230 S2 2015 Software Construction Applets & AWT.

Events, Listeners, Adapters and Handler Methods

Event Listener / Adapter Handler Methods

ActionEvent ActionListener actionPerformed

AdjustmentEvent AdjustmentListener adjustmentValueChanged

MouseEvent MouseListenerMouseAdapter

mouseClickedmouseEnteredmouseExitedmousePressedmouseReleased

KeyEvent KeyListenerKeyAdapter

keyPressedkeyReleasedkeyTyped

ComponentEvent ComponentListenerComponentAdapter

componentShowncomponentHiddencomponentMovedcomponentResized

1124

Page 25: CompSci 230 S2 2015 Software Construction Applets & AWT.

Buttons Constructors

Button(String buttonLabel) Useful Methods

getLabel/setLabel Retrieves or sets the current label

Event Processing Methods addActionListener/removeActionListener

Add/remove an ActionListener that processes ActionEvents in actionPerformed

General Methods Inherited from Component getForeground/setForeground getBackground/setBackground getFont/setFont

1125

Page 26: CompSci 230 S2 2015 Software Construction Applets & AWT.

One Vs Two One button:

Steps: Implements the ActionListener interface Create a button Add the button to the frame Add an ActionListener to the button Implement the actionPerformed method to handle the event

More than one button: Steps are similar to the above But you must use e.getSource() in the actionPerformed event

handler to check which button is pressed by the user.

public class SimpleButton extends Frame implements ActionListener { ... Button quit = new Button( "quit" ); add(quit); quit.addActionListener( this );

... public void actionPerformed( ActionEvent e ) { System.exit( 0 ); }

public void actionPerformed( ActionEvent e ) { if ( e.getSource( ) == quit ) { // System.exit( 0 ); } else if (e.getSource() == check) { count++; check.setLabel("" + count); }}

Example: SimpleButton.java

1126

Page 27: CompSci 230 S2 2015 Software Construction Applets & AWT.

TextField Constructors

TextField(fieldLabel) Useful Methods

getText/setText Retrieves or sets the text that is presented by this text component

Event Processing Methods addActionListener/removeActionListener

Add/remove an ActionListener that processes ActionEvents in actionPerformed

Note: the user must press 'enter' inside the text field to activate the event. public class SimpleTextField extends Frame implements ActionListener {

... value = new TextField("Enter a number"); copy = new TextField(20); value.addActionListener( this ); quit.addActionListener( this ); ... public void actionPerformed( ActionEvent e ) { copy.setText(value.getText()); } ...

Example: SimpleTextField.java

1127

Page 28: CompSci 230 S2 2015 Software Construction Applets & AWT.

public class PalindromeGUI2 extends Frame implements ActionListener {

private TextField text; private Button isPalindrome, quit; private Label output;

public PalindromeGUI2() { super( "Palindrome detector" ); … isPalindrome.addActionListener( this ); quit.addActionListener( this ); }

public void actionPerformed( ActionEvent e ) { if( e.getSource( ) == isPalindrome ) { // isPalindrome pressed. String enteredText = text.getText( ); if( enteredText.length( ) > 0 ) { if( isPalindromic( enteredText ) ) { output.setText( enteredText + " is palindromic" ); } else { output.setText( enteredText + " is not palindromic" ); } } } else { // quit pressed. System.exit( 0 ); } }}

PalindromeGUI / ActionListener instance

Button instance

isPalindrome

quit

listenerlistener

1: addActionListener( this )

2: actionPerformed( )

Button instance

Example: PalindromeGUI2.java

1128

Page 29: CompSci 230 S2 2015 Software Construction Applets & AWT.

Custom Painting in AWT

Container

Component

paint( g : Graphics ) : voidrepaint( ) : void

Panel

MousePositionPanel

<< interface >>MouseListener

Overrides paint( ) to print the location of the last mouse click

1129

Page 30: CompSci 230 S2 2015 Software Construction Applets & AWT.

Example: MouseListener Steps:

Implements the MouseListener interface Adds an MouseListener Implements 5 methods:

mousePressed mouseReleased mouseClicked mouseEntered mouseExited

Calls repaint(): to update the position

class MousePositionPanel extends Panel implements MouseListener { private int mouseX, mouseY;

public MousePositionPanel( ) { mouseX = 100; mouseY = 100; addMouseListener( this ); }

public void paint( Graphics g ) { g.drawString( "(" + mouseX + ", " + mouseY + ")", mouseX, mouseY ); } public void mousePressed( MouseEvent e ) { mouseX = e.getX( ); mouseY = e.getY( ); repaint( ); } public void mouseReleased( MouseEvent e ) { } public void mouseClicked( MouseEvent e ) { } public void mouseEntered( MouseEvent e ) { } public void mouseExited( MouseEvent e ) { }}

Example: MousePositionPanel.java

1130

Page 31: CompSci 230 S2 2015 Software Construction Applets & AWT.

No need to give inner classes names!public class PalindromeGUI3 extends Frame { private TextField text; private Button isPalindrome, quit; private Label output;

public PalindromeGUI3( ) { … isPalindrome.addActionListener( new ActionListener( ) { public void actionPerformed( ActionEvent e ) { String enteredText = text.getText( );

if( enteredText.length( ) > 0 ) if( isPalindromic( enteredText ) ) output.setText( enteredText + " is palindromic" ); else output.setText( enteredText + " is not palindromic" ); } } );

quit.addActionListener( new ActionListener( ) { public void actionPerformed( ActionEvent e ) { System.exit( 0 ); } } ); …}

PalindromeGUI instance

Button instance

isPalindrome

quit

listenerlistener

actionPerformed( )

Button instance

ActionListener instance

ActionListener instance

Anonymous Inner Classes

Note: don’t need to use the getSource()

method

have access to all instance variables of the

enclosing class

Example: PalindromeGUI3.java

1131