123
1 Java GUIs Dr. Randy M. Kaplan

1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

Embed Size (px)

Citation preview

Page 1: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

1

Java GUIs

Dr. Randy M. Kaplan

Page 2: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

2

Constructing User Interfaces

From a functionality standpoint there are two things that every program must implement Interaction Computation

Page 3: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

3

Constructing User Interfaces

As Java evolved as a browser based language, it provides a rich set of tools for interacting with a program user

Originally these tools were embodied in the java.awt or Abstract Windowing Toolkit

AWT is platform dependent Look and feel is determined by the platform

Java 2 incorporated the Swing components Look and feel is independent of the platform

Page 4: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

4

Constructing User Interfaces

Swing Component Advantages “Lightweight” Written entirely in Java Not weighed down by platform specific issues

Page 5: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

5

Model-View-Controller Architecture Swing

Loosely based on the Model-View-Controller architecture (MVC)

Model Stores data which defines the component

View Creates the visual representation of the component from the

data in the model Controller

Deals with the interaction with the component and modifies the model and/or the view in response to a user action as necesary

Page 6: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

6

Basics – 1

A CONTAINER is a collection of related components

The content pane is a container that will be used to contain the interface components

Components are added to a container with the add method

Page 7: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

7

Creating a Window

A basic window in Java is represented by an object of the class Window in the package java.awt

Objects of the class are hardly ever used directly because Borders and title bars are pretty much always part

of a window and the Class Window does not provide these

JFrame in javax.swing includes these features and others

Page 8: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

8

JFrame HierarchyObject

Component

Container

Window

Frame

JFrame

Defines a component, which isan object that can be display

such as a button or a scrollbar

Defines a component thatcontains other components

Defines a basic window withno title bar or border

Defines a window with a titlebar and a border

A frame with extendedcapabilities

Java.lang

Java.swing

{Java.awt

Page 9: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

9

Displaying an Application Window

Page 10: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

10

Components and Containers

Component Represents a graphical entity that can be

displayed on the screen Any object of a class that is a subclass of a

Component

Page 11: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

11

Key Classes in the Window Hierarchy JFrame

Basic Java Application Window Has

Title bar Provision for adding menu

Subclass this class to create a window class specific to your application

Page 12: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

12

Key Classes in the Window Hierarchy JDialog

Define a dialog window Enter data into a program in barious ways

JApplet Basic class for a Java 2 applet All Java 2 applets will have this class as a base

class Drawing is possible in a JApplet Add menus and other components

Page 13: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

13

Key Classes in the Window Hierarchy JComponent

Subclasses of JComponent define a range of standard components

Page 14: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

14

Window Panes

Add components or draw in a window displayed from a JFrame object – You add the components or draw on a window

pane that is managed by the JFrame object Window panes are objects that are

containers which represent an area of a window

Window panes come in several different types

Page 15: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

15

Window PanesEnter Title Here

Jframe Window

Optional menu bar

The area of the window below the titlebarcorresponds to a JRootPane object

layeredPane object of type JLayeredPane

contentPane object of type JInternalPane

The contentPane is where you would normally addcomponents other than a menubar to a window. A referenceto the contentpane is returned by getContentPane() member

of the Jframe object

Page 16: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

16

Window Panes

The area below the title bar in a JFrame corresponds to a JRootPane object

The JRootPane object contains another pane – the layeredPane

Enter Title Here

Jframe Window

Optional menu bar

The area of the window below the titlebarcorresponds to a JRootPane object

layeredPane object of type JLayeredPane

contentPane object of type JInternalPane

The contentPane is where you would normally addcomponents other than a menubar to a window. A referenceto the contentpane is returned by getContentPane() member

of the Jframe object

Page 17: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

17

Window Panes

The area below the title bar in a JFrame corresponds to a JRootPane object

The layeredpane area corresponds to the area occupied by JRootPane

If there is a menu bar it is managed by the layeredPane

Enter Title Here

Jframe Window

Optional menu bar

The area of the window below the titlebarcorresponds to a JRootPane object

layeredPane object of type JLayeredPane

contentPane object of type JInternalPane

The contentPane is where you would normally addcomponents other than a menubar to a window. A referenceto the contentpane is returned by getContentPane() member

of the Jframe object

Page 18: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

18

Window Panes

The area below the menu bar corresponds to the contentPane object

The contentPane object is where components are typically placed

Enter Title Here

Jframe Window

Optional menu bar

The area of the window below the titlebarcorresponds to a JRootPane object

layeredPane object of type JLayeredPane

contentPane object of type JInternalPane

The contentPane is where you would normally addcomponents other than a menubar to a window. A referenceto the contentpane is returned by getContentPane() member

of the Jframe object

Page 19: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

19

Window Panes

The layeredPane object has special properties

Advanced applications may permit groups of components to be managed in separate layers that overlay one another within the pane

Layers are displayed in order from back to front

Enter Title Here

Jframe Window

Optional menu bar

The area of the window below the titlebarcorresponds to a JRootPane object

layeredPane object of type JLayeredPane

contentPane object of type JInternalPane

The contentPane is where you would normally addcomponents other than a menubar to a window. A referenceto the contentpane is returned by getContentPane() member

of the Jframe object

Page 20: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

20

Window Panes

One additional pane, the glassPane object, corresponds to the JRootPane area

The glassPane displays on top of all the other panes

The glassPane is used to display components that will always remain on top

Enter Title Here

Jframe Window

Optional menu bar

The area of the window below the titlebarcorresponds to a JRootPane object

layeredPane object of type JLayeredPane

contentPane object of type JInternalPane

The contentPane is where you would normally addcomponents other than a menubar to a window. A referenceto the contentpane is returned by getContentPane() member

of the Jframe object

Page 21: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

21

JFrame Class Methods to access panesMethod Description

getRooPane() Returns the root pane as type JRootPane

getLayeredPane() Returns the root pane as type JLayeredPane

getContentPane() Returns the content pane as type Container. This is the method that you will use most frequently, since components will normally be added to this pane

getGlassPane() Returns the glass pane as type component

Page 22: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

22

Component Attributes

The component class defines attributes that record the following information about a component object Position Name Size Foreground color Background color Cursor Enabled Visible

Page 23: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

23

Methods for Size and Position setBounds(int x, int y, int width, int height) setBounds(Rectangle rect) Rectangle getBounds setSize(Dimension d) Dimension getSize() setLocation(int x, int y) setLocation(Point p) Point getLocation()

Page 24: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

24

Basics – 2

JComponent is the superclass to most Swing components

This class defines the common attributes and behaviors of all subclasses of JComponent

Page 25: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

25

Basics – 3

JLabel Subclass of JComponent Displays a

single line of read-only text

Image Text and image

Page 26: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

26

Basics – 4

Basic Interface Construction

Page 27: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

27

Using Containers

A container is any class with the Container class as its base class

All Swing components are containers The Container class is the direct base class

for the Window class which gives the Window class the ability to contain other object

Container is called an abstract class which means that instances of the Container class cannot be created

Page 28: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

28

Using Containers

Components within a container are displayed within the area of the container

A container controls how its embedded components are laid out by means of a layout manager

Page 29: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

29

Container Class

Basic Methods int getComponent()

Returns a count of the number of components contained by the current component

Component getComponent(int index) Returns the component identified by the index value

Component [] getComponents() Returns an array of components in the current container

Page 30: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

30

Container Class

Adding Components Components are recorded in an array within the

Container object The array is increased in size to accommodate as

many components as are present To add a component to a contained use the

method add()

Page 31: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

31

Add Methods

Component add(Component c) Add the component c to the end of the list of components

stored in the container Component add(Component c, int index)

Add the component c to the list of components in the container at the position specified by index

If index == -1 then the component is added to the end of the container

void add (Component c, Object constraints) void add (Component c, Object constraints, int

index)

Page 32: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

32

Basics – 4

Basic Interface Construction

A class is going to be defined that will extend the functionality of a graphics element container like a JFrame

Page 33: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

33

Basics – 5

Basic Interface Construction

The content pane contains what will be displayed. We need to retrieve it so we can use it to display our graphical components

Page 34: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

34

Basics – 6

Basic Interface Construction

Graphics elements like JLabel are created and added to the content pane

Page 35: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

35

Basics – 7

Basic Interface Construction

The size of the frame is set and the state of the frame is set to visible

Page 36: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

36

Basics – 8

Basic Interface Construction

A new instance of the class is created and the creation of it causes the instance of the JLabel to be displayed

Page 37: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

37

Events – 1

The previous class definition showed the basic elements of how a user interface element is added to a class method

Labels are static non-interactive interface elements

Besides being able to display elements we would also like to be able to capture interface element interactions

Page 38: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

38

Event-Driven Progams

Operating System

Keystrokes Keystrokes Mouse Actions

Java Library Classes

Program method method method method

Events

Page 39: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

39

Events – 2

Event Handling Three Parts

Event source Event object Event listener

Page 40: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

40

Events – 3

Event Handling Three Parts

Event source The particular interface component with which the user

interacts Event object Event listener

Page 41: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

41

Events – 4

Event Handling Three Parts

Event source Event object

Encapsulates information about the event that occurred Reference to the event source Specific event information that is required by the event

listener Event listener

Page 42: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

42

Events – 5

Event Handling Three Parts

Event source Event object Event listener

Receives an event object when it is notified of the event Uses the event object to respond to the event

Page 43: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

43

Events – 6

Two Key Programmer Responsibilities Register a listener for the event Implement an event handler for the event

Page 44: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

44

Events

What happens when an event occurs? A user clicks a button in the GUI for your program The button is the source of this event The event generated as a result of the mouse

click is associated with the JButton object in your program that represents the button on the screen

Page 45: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

45

Events

When the button is clicked – A new object is created The object represents and identifies this event For a button, the object is an instance of the class

ActionEvent The object will contain information about the event and its

source Any event that is passed to a Java program will be

represented by a particular event object The object will be passed as an argument to the

method that is to handle the event

Page 46: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

46

Events

Button

Click

OK

Creates

ActionEventobject

The listener connects to theevent source by calling

addActionListener() methodfor the source object

Passed to

public class MyButtonHandler implementsActionListener{

// class members// Constructor…button.addActionListener(this);…void actionPerformed(ActionEvent e){

// Handle the event}

}

Page 47: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

47

Events

The event object corresponding to the button click will be passed to any listener object that has previously registered an interest in this kind of event

A listener object is simply an object that listens for particular events

A listener object is also called a target for an event

Page 48: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

48

Defining a Listener

Objects of any class can be made listeners by implementing a listener interface

There are many kinds of listener interfaces that cater to the different kinds of events

Each kind of listener interface defines particular methods for receiving the events that that listener has been designed to deal with

In addition to implementing the listener, the listener has to be connected to its source

Page 49: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

49

Kinds of Events

Low-level Events Events arising from the keyboard or from the

mouse Events associated with operation on a window –

such as reducing it to an icon or closing it Semantic Events

Specific component related events Pressing a button by clicking it to cause some program

action Adjusting a scrollbar

Page 50: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

50

Low-level Events

FocusEvent Objects of this class represent events that originate when a

component gains or loses focus MouseEvent

Objects of this class represent events that result from user action with the mouse such as moving the mouse or pressing a mouse button

KeyEvent Objects of this class represent events that arise from pressing

keys on the keyboard WindowEvent

Objects of this class represent events that relate to a window such as activating or deactiviating a window, reducing a window to its icon or closing a window

Page 51: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

51

JTextField and JPasswordField – 1

Page 52: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

52

JTextField and JPasswordField – 2 Single-line areas Text is entered by a user Text can be displayed A JPasswordField shows that a character

was typed but hides the characters When the user presses the ENTER key in a

JTextField or JPasswordField an event occurs

Page 53: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

53

JTextField and JPasswordField – 3

Declare the text fields and add the fields to the container.

Page 54: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

54

JTextField and JPasswordField – 4

Each of the field gets an event handler

Page 55: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

55

JTextField and JPasswordField – 5

The main gets specified as before. Declare a new instance which causes the code of the instance to run

Page 56: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

56

JTextField and JPasswordField - 6

Page 57: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

57

JTextField and JPasswordField – 7

The listener that is used is a new class that extends the functionality of the ActionListener – the main class for implementing event Listeners

Page 58: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

58

JTextField and JPasswordField – 8

actionPerformed is an abstract method that is defined for ActionListener. This abstract method is invoked when an event occurs. It must be defined for the listener in order to respond to the event that occurs

Page 59: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

59

JTextField and JPasswordField – 8

When actionPerformed is invoked, it is pass event, an object that contains information about the event that just occurred. It is this object that is examined in the code that follows to determine what actually occurred in the event

Page 60: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

60

JTextField and JPasswordField – 9

The getSource method returns a reference to the interface object involved in the event. We can use this reference to make decisions about how to respond to the event

Page 61: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

61

JTextField and JPasswordField – 10

We can retrieve the specific command that occurred in an event with the getActionCommand() method

Page 62: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

62

Event Listeners

Each type of event has its associated listener Action events are handled by ActionListeners MouseEvents are handled by MouseListeners Key events are handled by KeyListeners

Page 63: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

63

Event Handling – 1

Let’s consider event handling in more detail There are two things that are important to

keep in mind when writing code to handle events

These are: Getting an event handler registered Connecting the GUI component to the code that

will execute when an action involving it is executed

Page 64: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

64

Event Handling – 2

An event has a listener registered for it using code like the following – textField1.addActionListener( handler ); textField2.addActionListener( handler ); textField3.addActionListener( handler );

Every JComponent has an object of class EventListenerList called listenerList as an instance variable

All registered listeners are stored in the listenerList

Page 65: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

65

Event Handling – 3

When the statement, textField1.addActionListener( handler );

is executed, a new entry is placed in the listenerList for textField1

Both a reference to the listener object and type of listener are recorded

Page 66: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

66

Event Handling – 4

Types of Listeners How does a GUI component know to call the correct event

handling method? Every component supports several event types

Mouse events Key events Action events

When an event occurs, the event is dispatched only to those listeners of the appropriate type

The dispatch simply is calling the event handling method for each registered listener for that event type

Page 67: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

67

Event Handling – 5

Each event Has a corresponding event-listener interface ActionEvents

Are handled by ActionListeners MouseEvents

Are handled by MouseListeners KeyEvents

Are handled by KeyListeners

Page 68: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

68

Event Handling – 6

When an event occurs – A user generates an interaction with a component The component is handed a unique event ID

The event ID specifies the event type that occurred The GUI component uses the event ID to decide the type of

listener In the case of an ActionEvent, the event is dispatched to

every registered ActionListener’s actionPerformed method In the case of a MouseEvent, the event is dispatched to every

registered MouseListener The event ID of the MouseEvent determines which of the seven

different mouse event handling methods are called

Page 69: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

69

JButton

A button is a component that a user clicks to trigger a specific action

There are several different types of buttons – Command buttons Check boxes Toggle buttons Radio buttons

Page 70: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

70

JButton

When the ButtonTest program is run, a panel with two buttons is displayed

Page 71: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

71

JButton

plainButton = new JButton( "Plain Button" ); container.add( plainButton );

Icon bug1 = new ImageIcon( "c:\\javaprj\\bug1.gif" ); Icon bug2 = new ImageIcon( "c:\\javaprj\\bug2.gif" ); fancyButton = new JButton( "Fancy Button", bug1 ); fancyButton.setRolloverIcon( bug2 ); container.add( fancyButton );

Page 72: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

72

JButton ButtonHandler handler = new ButtonHandler(); fancyButton.addActionListener( handler ); plainButton.addActionListener( handler );

Code that registers the event handlers for each of the buttons

private class ButtonHandler implements ActionListener { public void actionPerformed( ActionEvent event ) { JOptionPane.showMessageDialog( null, "You pressed: " + event.getActionCommand() ); } }

The event handler shows a message dialog that displays the name of the button that was clicked

Page 73: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

73

JCheckBox and JRadioButton

Swing has three types of state buttons JToggleButton

Frequently used in toolbars JCheckBox

Individual boxes that can be checked JRadioButton

Groups of buttons in which only one can be set

Page 74: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

74

JCheckBox

A check box allows the state of this UI component to be set or unset

The check box UI components are independent of one another

Page 75: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

75

JCheckBox

The event handler for these checkboxes contains the code to change the font characteristics of the text box

private class CheckBoxHandler implements ItemListener { private int valBold = Font.PLAIN; private int valItalic = Font.PLAIN;

// respond to checkbox events public void itemStateChanged( ItemEvent event ) { // process bold checkbox events if ( event.getSource() == bold )

if ( event.getStateChange() == ItemEvent.SELECTED ) valBold = Font.BOLD; else valBold = Font.PLAIN; // process italic checkbox events if ( event.getSource() == italic )

if ( event.getStateChange() == ItemEvent.SELECTED ) valItalic = Font.ITALIC; else valItalic = Font.PLAIN;

// set text field font field.setFont( new Font( "Serif", valBold + valItalic, 14 ) ); } }

Page 76: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

76

JCheckBox private class CheckBoxHandler implements ItemListener { private int valBold = Font.PLAIN; private int valItalic = Font.PLAIN;

// respond to checkbox events public void itemStateChanged( ItemEvent event ) { // process bold checkbox events if ( event.getSource() == bold )

if ( event.getStateChange() == ItemEvent.SELECTED ) valBold = Font.BOLD; else valBold = Font.PLAIN; // process italic checkbox events if ( event.getSource() == italic )

if ( event.getStateChange() == ItemEvent.SELECTED ) valItalic = Font.ITALIC; else valItalic = Font.PLAIN;

// set text field font field.setFont( new Font( "Serif", valBold + valItalic, 14 ) ); } }

The type of listener required for the checkBox GUI component is an ITEMLISTENER

Page 77: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

77

JCheckBox private class CheckBoxHandler implements ItemListener { private int valBold = Font.PLAIN; private int valItalic = Font.PLAIN;

// respond to checkbox events public void itemStateChanged( ItemEvent event ) { // process bold checkbox events if ( event.getSource() == bold )

if ( event.getStateChange() == ItemEvent.SELECTED ) valBold = Font.BOLD; else valBold = Font.PLAIN; // process italic checkbox events if ( event.getSource() == italic )

if ( event.getStateChange() == ItemEvent.SELECTED ) valItalic = Font.ITALIC; else valItalic = Font.PLAIN;

// set text field font field.setFont( new Font( "Serif", valBold + valItalic, 14 ) ); } }

When the state of a check box is changed, the method itemStateChanged is invoked

Page 78: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

78

JCheckBox private class CheckBoxHandler implements ItemListener { private int valBold = Font.PLAIN; private int valItalic = Font.PLAIN;

// respond to checkbox events public void itemStateChanged( ItemEvent event ) { // process bold checkbox events if ( event.getSource() == bold )

if ( event.getStateChange() == ItemEvent.SELECTED ) valBold = Font.BOLD; else valBold = Font.PLAIN; // process italic checkbox events if ( event.getSource() == italic )

if ( event.getStateChange() == ItemEvent.SELECTED ) valItalic = Font.ITALIC; else valItalic = Font.PLAIN;

// set text field font field.setFont( new Font( "Serif", valBold + valItalic, 14 ) ); } }

We check the current state of each of the check boxes and set the font characteristics accordingly

Page 79: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

79

JCheckBox private class CheckBoxHandler implements ItemListener { private int valBold = Font.PLAIN; private int valItalic = Font.PLAIN;

// respond to checkbox events public void itemStateChanged( ItemEvent event ) { // process bold checkbox events if ( event.getSource() == bold )

if ( event.getStateChange() == ItemEvent.SELECTED ) valBold = Font.BOLD; else valBold = Font.PLAIN; // process italic checkbox events if ( event.getSource() == italic )

if ( event.getStateChange() == ItemEvent.SELECTED ) valItalic = Font.ITALIC; else valItalic = Font.PLAIN;

// set text field font field.setFont( new Font( "Serif", valBold + valItalic, 14 ) ); } }

Lastly, the font of the field is set to change the visible characteristics of the font

Page 80: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

80

Layouts

You have seen the following code used container.setLayout( new FlowLayout() );

This code specifies the type of layout that will be used to place the components in the display container

What exactly is a flow layout?

Page 81: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

81

Layouts

Layouts managers are provided to arrange components on a container for presentation purposes

The idea is that by providing these managers it is easier than specifying the exact positions of the components

Programmers concentrate on basic look and feel and the layout manager takes care of the rest

Page 82: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

82

Layouts

Types of Layouts FlowLayout

Components are placed sequentially left to right in the order they were added

Default layout manager for Applet Panel JPanel

BorderLayout GridLayout

Page 83: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

83

Layouts

Types of Layouts FlowLayout BorderLayout

Arranges the components into five areas – North, South, East, West, and Center

Default for JFrame GridLayout

Page 84: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

84

Layouts

Types of Layouts FlowLayout BorderLayout GridLayout

Arranges the components into rows and columns

Page 85: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

85

FlowLayout

Most basic layout manager Components are placed left to right in the

order they are added to the container When the edge of the container is reached,

components are continued on the next line Components can be

Left aligned Centered (default) Right aligned

Page 86: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

86

FlowLayout

The next example creates three buttons in a FlowLayout

Buttons are labeled Left Center Right

Clicking left Sets the flow layout alignment to left

Clicking right Sets the flow layout alignment to right

Clicking center Sets the flow layout alignment to center

Page 87: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

87

FlowLayout

Left Aligned

Centered

Right Aligned

Page 88: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

88

FlowLayout

The “container” is a JFrame

Page 89: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

89

FlowLayout

Create the layout object

Page 90: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

90

FlowLayout

Get the container’s content pane

Page 91: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

91

FlowLayout

Set the layout to be a flowlayout (set the container’s layout)

Page 92: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

92

FlowLayout

Setting up a button

Create the new button

Page 93: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

93

FlowLayout

Setting up a button

“On the fly”, create an instance of a listener class.

This is called an “inner class” because it is defined with another class

It is “anonymous” because it is defined ONLY for this button

Page 94: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

94

FlowLayout

Setting up a button

The action to be performed is to set the layout’s alignment – in this case to left aligned

Page 95: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

95

FlowLayout

Setting up a button

The layout if forced to realign (visibly) due to this statement

Page 96: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

96

FlowLayout

Setting up a button

Once the action has been defined for the button, it is added to the container

Page 97: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

97

BorderLayout

BorderLayout Is the default layout for the contain pane Arranges components into five regions

NORTH SOUTH EAST WEST CENTER

Up to 5 components can be added to a BorderLayout The component placed in a region can actually be another

container to contain other components

Page 98: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

98

BorderLayout

Schematic View of Regions

North

South

East WestCenter

As tall as component placed in the region

As wide as the component placed in the region

Page 99: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

99

BorderLayout

Schematic View of Regions

North

South

Center

If the EAST and WEST regions are not occupied, the center region expands to fill the regions

Page 100: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

100

BorderLayout

Schematic View of Regions

East WestCenter

If the NORTH and SOUTH regions are not occupied, EAST and WEST expand vertically

Page 101: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

101

BorderLayout

Example

Horizonal gap between components

Vertical gap between components

Default gap is 0 (ZERO) pixels

Page 102: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

102

GridLayout

Divides the container into a grid Components are laid out in rows and

columns Every component in a grid layout has the

same width and height Components are added to a grid

Left to right Top to bottom Until the grid is full

Page 103: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

103

GridLayout

Example

Page 104: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

104

GridLayout

Create two layouts

Page 105: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

105

GridLayout

The first layout has 2 rows and 3 columns, and

the inter row/column spacing is 5

pixels

Page 106: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

106

GridLayout

The second layout contains

3 rows and 2 columns and

the inter row/column spacing is 0

pixels

Page 107: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

107

GridLayout

The buttons are added to the

container here

Page 108: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

108

GridLayout

The total dimensions of the container

are defined here

The buttons of the layout are

sized according to the total dimension

Page 109: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

109

GridLayout

Changing the dimension to 500 x 500

Page 110: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

110

Panels

When a complex GUI is designed It is desirable to place components in an exact

location Complex GUI’s often consist of multiple PANELS Components within a panel are arranged in a

specific layout

Page 111: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

111

Example

Get the containing content frame

Page 112: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

112

Example

Create and array to hold 5 buttons

Page 113: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

113

Example

Create the panel that will contain the buttons

Page 114: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

114

Example

Set the layout of the panel containing the buttons to be a 1 row x # of buttons grid layout

Page 115: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

115

Example

Create 5 buttons and add them to the panel that contains them

Page 116: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

116

Example

Add the panel to the frame in the southern position

Page 117: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

117

Adapter Classes

Many event-listener classes provide multiple methods For example

MouseListener MouseMotionListener

It is not always desirable to define every method in an event listener interface

Page 118: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

118

Adapter Classes

For example When a windowed application is terminated

A method named windowClosing is invoked from the interface WindowListener

WindowListener specifies seven window-event handling methods

Page 119: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

119

Adapter Classes

In order to avoid implementing all of the listener methods Java provides adapter classes

An adapter class Implements an interface Provides a default implementation

Usually has an empty body Can be extended with specific functionality when

required

Page 120: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

120

Adapter Classes

Event Adapter Class ComponentAdapter ContainerAdapter FocusAdapter KeyAdapter MouseAdapter MouseMotionAdapter WindowAdapter

Implements Interface ComponentListener ContainerListener FocusListener KeyListener MouseListener MouseMotionListener WindowListener

Page 121: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

121

Example

We add a mouse motion listener and define an instance of a class MouseMotionAdapter to define functionality for the dragging of the mouse. xValue and yValue will record the current position of the mouse

Page 122: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

122

Example

The repaint() method causes the frame to be redrawn and this is accomplished by the paint() method

The paint() method draws a small oval at the recorded xValue and yValue

Page 123: 1 Java GUIs Dr. Randy M. Kaplan. 2 Constructing User Interfaces From a functionality standpoint there are two things that every program must implement

123

Class Exercise

Write Java code to create the interface shown below (do not worry about its functionality)