32
Unit 10 1 Java GUI Components and Events GUI Components and Containers Adding Components to Containers GUI Events GUI Events Classes Learning Outcomes o Distinguish between GUI components and containers. o Identify and distinguish top-level containers from other containers. o Write simple programs to add components into containers. o Explain what Events are, and distinguish between Event sources, Event classes and Event listeners.

Unit 101 Java GUI Components and Events GUI Components and Containers Adding Components to Containers GUI Events GUI Events Classes Learning

  • View
    364

  • Download
    0

Embed Size (px)

Citation preview

Unit 10 1

Java GUI Components and Events

GUI Components and Containers Adding Components to Containers GUI Events GUI Events Classes Learning Outcomes

o Distinguish between GUI components and containers.

o Identify and distinguish top-level containers from other containers.

o Write simple programs to add components into containers.

o Explain what Events are, and distinguish between Event sources, Event classes and Event listeners.

Unit 10 2

Introduction to Components

• A component is an object having a graphical representation that can be displayed on the screen.

• Example of components in a typical GUI include:• buttons, text boxes, lables and pop-up menus

Unit 10 3

Introduction to Containers

A container is a special component that can hold other components.• Example of containers in typical

GUI applications include:o panels, windows, applets, frames

• Functionality of most GUI

components derive from the

Component and Container classes.

Unit 10 4

Anatomy of Top-level Containers

• Each top-level container has only one component, JRootPane.

• The root pane consists of three other containers: the layered, content and glass panes:

Unit 10 5

Anatomy of Top-level Containers (cont’d)

• The root pane has a glass pane on top and a layered pane underneath.

• The glass pane component is

always painted last and appears

on top of the content pane and

menu bar.

• The layered pane consists of

a menu bar and a content pane.

• A content pane is a Container that covers the visible area

of a container.

• A content pane is automatically created for a newly created container.

• Components must be added to the content pane of a container.

• The content pane can be retrieved using the getContentPane method.

Unit 10 6

Anatomy of an Application GUI

JPanel

JButton

JFrame

JLabelGUI

Internal structure

JFrame

JPanel

JButton JLabel

containers

Unit 10 7

Frames

• Frame is a window that is not contained inside another window. Frame is the basis to contain other user interface components in Java GUI applications.

• The Frame class can be used to create windows.

• For Swing GUI programs, use JFrame class to create widows.

import javax.swing.*;public class MyFrame { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(400, 300); frame.setVisible(true);

// Add a button into the frame frame.getContentPane().add(new JButton("OK"));

frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); }

}

Unit 10 8

NOTE

• The content pane is a subclass of Container. The statement in the

preceding slide can be replaced by the following two lines:

• Container container = frame.getContentPane();

• container.add(new JButton("OK"));

• You may wonder how a Container object is created. It is created

when a JFrame object is created.

• A JFrame object uses the content pane to hold components in the

frame.

Unit 10 9

Centering Frames

screenHeight

screenWidth

getHeight()

getWidth()

(x, y)

Frame

Screen

(0, 0)

• By default, a frame is displayed in the upper-left corner of the screen.

• To display a frame at a specified location, you can use the setLocation(x, y)

method in the JFrame class.

• This method places the upper-left corner of a frame at location (x, y).

Unit 10 10

Your First Swing Program

• Import Swing package

– Import javax.swing.*;

– java.awt.* and java.awt.event.*

• At least one top-level container

– JFrame, JDialog, JApplet

– JFrame frame = new JFrame(“HelloWorld”);

– setVisible(true); pack();

• Create Swing components and add to content pane of frame

– JLabel label = new JLabel(“Hello World”);

– frame.getContentPane().add(label);

Unit 10 11

Your First Swing Program

import javax.swing.*;public class HelloWorld extends JFrame {

public HelloWorld() {JLabel label = new JLabel("HelloWorld!");// add component to frame’s containergetContentPane().add(label);// make frame visiblesetVisible(true);// resize if necessarypack();

}public static void main(String[] args) {

// create the frameHelloWorld frame = new HelloWorld();

}}

Unit 10 12

Example 1: Very Simple Swing Demonstration

import javax.swing.*;import java.awt.*; // not always necessary, but often includedpublic class FirstSwingDemo{ public static final int WIDTH = 300; public static final int HEIGHT = 200;

public static void main(String[] args) { JFrame myWindow = new JFrame(); myWindow.setSize(WIDTH, HEIGHT); JLabel myLabel = new JLabel(“Please don’t click that button!”); myWindow.getContentPane().add(myLabel);

WindowDestroyer myListener = new WindowDestroyer(); myWindow.addWindowListener(myListener);

myWindow.setVisible(true); }}

Unit 10 13

Notes on the Simple Demo Program

import javax.swing.*;public class FirstSwingDemo{ public static final int WIDTH = 300; public static final int HEIGHT = 200;

public static void main(String[] args) { JFrame myWindow = new JFrame(); myWindow.setSize(WIDTH, HEIGHT); JLabel myLabel = new JLabel(“Please don’t click…”); myWindow.getContentPane().add(myLabel);

WindowDestroyer myListener = new WindowDestroyer(); myWindow.addWindowListener(myListener);

myWindow.setVisible(true); }}

Used in all Swing programs

Creates a JFrame window named myWindow

Adds a label to the JFrame window—note use of getContentPane

Unit 10 14

Notes on the Simple Demo Program

import javax.swing.*;public class FirstSwingDemo{ public static final int WIDTH = 300; public static final int HEIGHT = 200;

public static void main(String[] args) { JFrame myWindow = new JFrame(); myWindow.setSize(WIDTH, HEIGHT); JLabel myLabel = new JLabel(“Please don’t click…”); myWindow.getContentPane().add(myLabel); WindowDestroyer myListener = new WindowDestroyer(); myWindow.addWindowListener(myListener); myWindow.setVisible(true); }}

Allows the program to respond to the event of a user clicking in the close box.

WindowDestroyer is a programmer-defined class.

Unit 10 15

The Window Destroyer Class

public class WindowDestroyer extends WindowAdapter{ public void windowClosing(WindowEvent e) { System.exit(0); }}

WindowAdapter is a class that includes all the methods required for window events.

When a window closing event occurs, this method will be called and the program will quit.

Unit 10 16

The Results of the Simple Demo Program

import javax.swing.*;public class FirstSwingDemo{ public static final int WIDTH = 300; public static final int HEIGHT = 200;

public static void main(String[] args) { JFrame myWindow = new JFrame(); myWindow.setSize(WIDTH, HEIGHT); JLabel myLabel = new JLabel(“Please don’t click…”); myWindow.getContentPane().add(myLabel);

WindowDestroyer myListener = new WindowDestroyer(); myWindow.addWindowListener(myListener);

myWindow.setVisible(true); }}

The window will not show up on the screen without a line like this one.

Unit 10 17

Example 2: Creating Windows & Frames

1 import java.awt.*; import javax.swing.*; 2 public class TopLevelWindows{ 3 public static void main(String [] args){ 4 JFrame frame = new JFrame("My JFrame"); 5 frame.setLocation(100,100); 6 frame.setSize(300,300); 7 Container fcp = frame.getContentPane(); 8 JButton fb = new JButton("Draggable, Resizable Frame"); 9 fcp.add(fb);1011 JWindow window = new JWindow();12 window.setLocation(500,100);13 window.setSize(300,300);14 Container wcp = window.getContentPane();15 JButton wb = new JButton("Unmovable, No Frills Window");16 wcp.add(wb);1718 frame.setVisible(true);19 window.setVisible(true);20 }21 }

Unit 10 18

Example 3: Adding Components to Containers

1 import java.awt.*; 2 import javax.swing.*; 3 public class AddingComponents extends JFrame{ 4 5 JButton button = new JButton("Press Me"); 6 JLabel label = new JLabel( "Running Total:"); 7 JTextField textField = new JTextField(10); 8 Container cp = getContentPane(); 910 public AddingComponents() {11 super("A Container With Components");12 setSize(300,100);13 cp.setLayout(new FlowLayout());14 cp.add(label);15 cp.add(textField);16 cp.add (button);17 setVisible(true);18 }19 public static void main(String args []) {20 new AddingComponents();21 }22 }

Unit 10 19

Introduction to GUI Events

• We will now discuss how components and containers communicate.

• When a user interacts with a GUI component, events are triggered.

• An event is an action triggered by the user or by some other means.• For example, we may want our program to perform some action when the

following occurs:– The mouse is moved– A mouse button is clicked– The mouse is dragged– A graphical button is clicked– A keyboard key is pressed– A timer expires

• When an event is triggered an event object is created and delivered to the event receivers.

• Execution of these kinds of programs is driven by users’ activation of events.• Event classes, event sources and event listeners are three groups of Java classes

crucial for event-driven programming.

Unit 10 20

Events and Listeners

Generator

This object mayThis object maygenerate an eventgenerate an event

Listener

This object waits for andThis object waits for andresponds to an eventresponds to an event

Event

When an event occurs, the generator calls the appropriate method of the When an event occurs, the generator calls the appropriate method of the listener, passing an object that describes the event.listener, passing an object that describes the event.

• The Java standard class library contains several classes that represent typical events

• Certain objects, such as an applet or a graphical button, generate (fire) an event when it occurs

• Other objects, called listeners, respond to events

• We can write listener objects to do whatever we want when an event occurs

Unit 10 21

Listener Interfaces

• We can create a listener object by writing a class that implements a particular listener interface.

• The Java standard class library contains several interfaces that correspond to particular event categories.

• The MouseListener interface contains methods that correspond to mouse events

• After creating the listener, we add the listener to the component that might generate the event to set up a formal relationship between the generator and listener.

• The following are called key events:

– key pressed: a keyboard key is pressed down

– key released: a keyboard key is released

– key typed: a keyboard key is pressed and released

• The KeyListener interface handles key events

• Listener classes are often implemented as inner classes, nested within the component that they are listening to.

Unit 10 22

Mouse Events

• The following are mouse events:

– mouse pressed: the mouse button is pressed down

– mouse released: the mouse button is released

– mouse clicked: the mouse button is pressed and released

– mouse entered: the mouse pointer is moved over a particular component

– mouse exited: the mouse pointer is moved off of a particular component

• The following are called mouse motion events:

– mouse moved: the mouse is moved

– mouse dragged: the mouse is moved while the mouse button is held down

• There is a corresponding MouseMotionListener interface

• One class can serve as both a generator and a listener

• One class can serve as a listener for multiple event types

Unit 10 23

Events Classes Hierarchy

• Event classes represent events and contain methods for getting information on the events.

• Here is the class hierarchy

for events classes:

Unit 10 24

Events Source Classes

• An event source is the component that generates an event.

• A source must register listeners who may wish to take some action when the event is generated.

• When an event occurs the source informs all registered listeners for this event.

• An event listener can register or un-register with the following methods:

1. public void addTypeListener(TypeListener t)button.addActionListener(new ActionListener();

2. public void removeTypeListener (TypeListener t)

button.removeActionListener(new ActionListener();

• Type is the name of the event and t is a reference to the event listener.

Unit 10 25

Events Listener Classes

• The java.awt.event package contains interfaces and classes for dealing with events.

• Each listener interface is a specification for receiving a particular type of event.

• An event listener class implements the listener interfaces of interest to the class.

• Every event handler should satisfy these two conditions: 1. Implement an interface.

2. Register as event listener.

Unit 10 26

Types of Listeners

• ActionListener

• KeyListener, MouseListener, MouseMotionListener, TextListener

• AdjustmentListener, ComponentListener, ContainerListener, FocusListener, WindowListener

• Listeners are Interfaces.

Unit 10 27

Events: A Pictorial View

Unit 10 28

Mohamed

ICS

Student Data EntryForm

Unit 10 29

import java.awt.*;

public class EntryForm{ private Frame frame; private Button enterBtn; private TextField nameTxf; private TextField majorTxf; private TextField gpaTxf; private TextField creditsTxf;// constructor public EntryForm () {

Student Data EntryForm

Unit 10 30

// create components frame = new Frame ("Student Data Entry Form"); nameTxf = new TextField (20); majorTxf = new TextField (20); gpaTxf = new TextField (3); creditsTxf = new TextField (3); enterBtn = new Button ("Enter"); // add components to frame frame.setLayout (new FlowLayout()); frame.add (new Label ("Name")); frame.add (nameTxf); frame.add (new Label ("Major"));

Student Data EntryForm

Unit 10 31

frame.add (majorTxf); frame.add (new Label ("GPA")); frame.add (gpaTxf); frame.add (new Label ("Credits")); frame.add (creditsTxf); frame.add (enterBtn); // show frame frame.pack(); frame.setVisible (true); } // end of constructor} // end of classpublic class EntryFormApp{ // main program public static void main (String[] args) { new EntryForm(); }}

Student Data EntryForm

Unit 10 32

Exercises

1. The Panel, Window and JComponent class each subclasses Component class. Write

down the similarities and differences between these classes in a tabular form.

2. Write down in tabular form the similarities and differences between top-level

components and other GUI components.

3. Write a Java program to display three frames as follows. The top-left corner of the

second frame should have the same coordinates as the bottom-right corner of the first

frame. Similarly, the top-left corner of the third frame should have the same

coordinates as the bottom-right corner of the second frame.

4. Run the program in Example 2. Try resizing the window and watch how the

components placements change. Modify this program by adding four more buttons.

Remove the setSize method call and replace it with the call to the pack method.

Re-run the program and notice the output.

5. Write short notes on

a. Event classes

b. Event sources

c. Event listeners