92
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis as modified for CSCI 1260 Chapter 12: GUI Applications–Part 1

Starting Out with Java: Early Objects Third Edition by Tony Gaddis as modified for CSCI 1260

  • Upload
    gryta

  • View
    67

  • Download
    0

Embed Size (px)

DESCRIPTION

Chapter 11: GUI Applications – Part 1. Starting Out with Java: Early Objects Third Edition by Tony Gaddis as modified for CSCI 1260. Chapter Topics. Chapter 11 discusses the following main topics: Introduction Dialog Boxes Creating Windows Equipping GUI Classes with a main method - PowerPoint PPT Presentation

Citation preview

Page 1: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Starting Out with Java: Early Objects Third Edition

by Tony Gaddis as modified for CSCI 1260

Chapter 12:GUI Applications–Part 1

Page 2: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-2

Chapter Topics

Chapter 12 discusses the following main topics:IntroductionCreating WindowsEquipping GUI Classes with a main methodLayout ManagersRadio Buttons and Check BoxesBordersFocus on Problem Solving: Extending Classes from JPanel

Splash ScreensUsing Console Output to Debug a GUI Application

Page 3: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-3

Introduction• Many Java applications use a graphical user

interface or GUI (pronounced “gooey”)• A GUI is a graphical window or windows that provide

interaction with the user• GUI’s does not use the console window, but they

accept input from:the keyboarda mouse

• A window in a GUI consists of components that:present data to the userallow interaction with the application

Page 4: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-4

Introduction

• Some common GUI components are:buttons, labels, text fields, check boxes, radio

buttons, combo boxes, and sliders

Button

Text field Combo Box Check box

List control

Radio buttons

Slider control

Frame with caption, icon, and buttons

Label

Page 5: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-5

JFC, AWT, Swing

• Java programmers use the Java Foundation Classes (JFC) to create GUI applications

• The JFC consists of several sets of classes, many of which are beyond our scope

• The two sets of JFC classes that we focus on are AWT and Swing classes

• These classes are part of the Abstract Windowing Toolkit (AWT)This set of classes is for drawing graphics and creating

graphical user interfaces

Page 6: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-6

JFC, AWT, Swing

• The AWT allows creation of applications and applets with GUI components

• The AWT does not actually draw user interface components on the screen

• The AWT communicates with a layer of software in the operating system called peer classes

• Each version of Java for a particular operating system has its own set of peer classesIn other words, AWT lets each operating system draw

its own windows and GUI controls

Page 7: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-7

JFC, AWT, Swing• Java programs using the AWT:

look consistent with other applications on the same system

can offer only components that are common to all the operating systems that support Java

• The behavior of components across various operating systems can differ

• Programmers cannot easily extend the AWT components

• AWT components are commonly called heavyweight components because of their dependence on the operating system

Page 8: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-8

JFC, AWT, Swing• Swing was introduced with the release of Java 2

Now at Java 8

• Swing is a library of classes that provide an improved alternative for creating GUI applications and applets

• Very few Swing classes rely on peer classes, so they are referred to called lightweight components

• Swing draws most of its own components• Swing components have a consistent look and

predictable behavior on any operating system• Swing components can be extended easily

Page 9: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-9

javax.swing and java.awt

• In an application that uses Swing classes, it is necessary to use the following statement:

import javax.swing.*;Note the letter x that appears after the word java in javax

• Some of the AWT classes are used to determine when events, such as the clicking of a mouse, moving the cursor, pressing a key, scrolling, and so forth, take place in applications

• In an application that uses an AWT class, it is necessary to use the following statement

import java.awt.*;Note: there is no x after java in this package name

Page 10: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-10

Eclipse Tip• It is tedious to import classes or packages

manually one at a time• In Eclipse, one may use a “Consume First”

approach to get Eclipse to help . . . Type a Java instruction that uses a class for which no

“import” has been specified yetEclipse will put a red squiggly line underneath the not-

yet-imported class name

Press shift-ctrl-O and Eclipse will generate the proper import command if the class name is valid

Page 11: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-11

Event Driven Programming• Programs that operate in a GUI environment must be event-

driven• An event is something that happens (possibly the result of a

user action) while running a program, such as Clicking a button

Pressing a key on the keyboard

Moving a mouse

Selecting an item from a list or a menu

• Part of writing a GUI application is creating event listeners• An event listener is an object that automatically executes one

of its methods when its specific event occurs. It does something in response to the event that happened

Page 12: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-12

Stopping a GUI Program

• A GUI program does not automatically stop executing when the end of the main method is reached

• Swing generates a thread, which is a task running in the JVM

• If the System.exit method is not called, this thread continues to execute

Page 13: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-13

Stopping a GUI Program• The System.exit method requires an integer

argument

System.exit(0);This argument is an exit code that is passed back to the

operating systemThis exit code is usually ignored, however, it can be used

outside the program: to indicate whether the program ended successfully or as the result

of a failure

The value 0 traditionally indicates that the program ended successfully

Page 14: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-14

Creating Windows• Often, applications need one or more windows with various

components

• A window has 3 distinct but interrelated roles A window is a Java object just like other objects such as Strings,

Employees, Customers, Students, … It has attributes and methods just like other types of objects, and it may interact with other objects

A window has a graphical depiction on the screen as the program runs

A window is a container, which is simply a component that holds other components such as labels, buttons, captions, text fields, and so forth

• A container that can be displayed as a window is called a frame• In a Swing application, you may either

Create a frame directly from the JFrame class

Derive a new class from the JFrame class and create an object from it

Page 15: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-15

Creating Windows

• A frame is a basic window that has:a border around ita title bara set of buttons for:

minimizingmaximizing

closing the window

• These standard features are sometimes referred to as window decorations

Page 16: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-16

Creating Windows• In the main method, two constants are declared in the example

coming in few slides:final int WINDOW_WIDTH = 350, WINDOW_HEIGHT = 250;

• We use these constants later in the program to set the size of the window

• The window’s size is measured in pixels• A pixel (picture element) is one of the small dots that make up

a screen display

• The actual size of the window on the screen depends not only on its height and width, but also on the screen resolution A 350 x 250 window will be fairly large on a 640 x 480 screen, but it will

be much smaller on a 1920 x 1080 screen

Page 17: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-17

Creating Windows

• An instance of the JFrame class needs to be created:JFrame window = new JFrame("A Simple Window");

This statement:creates a JFrame object in memory and

assigns its address to the window variable

• The string that is passed to the constructor will appear in the window’s title bar when it is displayed; it is the caption for the window

• A JFrame is initially invisible

Page 18: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-18

Creating Windows• To set the size of the window:

window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);

• To specify the action to take place when the user clicks on the close button

window.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

• The setDefaultCloseOperation method takes an int argument which specifies the actionJFrame.HIDE_ON_CLOSE - causes the window to be

hidden from view, but the application does not end

The default action is JFrame.HIDE_ON_CLOSE

Page 19: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-19

Creating Windows• The following code displays the window by

making it visible on the screen:window.setVisible (true);

• The setVisible method takes a boolean argumenttrue - display the window

false - hide the window (this is default)

• You may use setTitle (string) to modify the window’s title (caption)window.setTitle(“My First GUI App”);

Page 20: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-20

A First Example

Page 21: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-21

Adding Components

• Swing provides numerous components (controls) that can be added to a window

• Three fundamental controls are:JLabel: An area that can display text

JTextField : An area in which the user may type a single line of input from the keyboard

JButton: A button that can cause an action to occur when it is clicked

• Objects of these classes can be created and used inside a window

Page 22: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-22

Sketch of Kilometer Converter Graphical User Interface

Window Title

Label

Button

Text Field

Page 23: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-23

Adding Componentsprivate JLabel messageLabel;private JTextField kiloTextField;private JButton calcButton;…messageLabel = new JLabel( "Enter a distance in kilometers");kiloTextField = new JTextField(10);calcButton = new JButton("Calculate");

• This code declares and instantiates three Swing components named:messageLabel (a JLabel object)kiloTextField (a JTextField object)calcButton (a JButton object)

Width of the TextField is 10 characters – a character

width is measured using an “m”, the widest character in

the alphabet.

Page 24: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-24

Class Hierarchy

AWT above this line,

Swing below it

Note the naming conventions – concrete Swing class

names almost always start with “J”

Page 25: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-25

Adding Components• A content pane is a container that is part of every JFrame object

• Every component added to a JFrame must be added to its content pane. You do this with the JFrame class's add method

• The content pane is not visible and it does not have a border

• A panel is another container that can hold GUI components – see JPanel

This area can be “thought of” as where the

content pane is

Page 26: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-26

Adding Components

• Panels cannot be displayed by themselvesUsually added to content pane or even to other panels

• Panels are commonly used to hold and organize collections of related components

• Create panels with the JPanel classprivate JPanel panel;…panel = new JPanel( );panel.add (messageLabel);panel.add (kiloTextField);panel.add (calcButton);

Page 27: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-27

Example Window with 3 Panels

Header panel has 2 controls

Selection Panel has 6 checkboxes

and 3 label controls

Button Panel has 2 button controls

Page 28: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-28

Adding Components

• Components are typically placed on a panel and then the panel is added to the JFrame's content pane

add(panel);

• Examples: KiloConverterWindow.java, KilometerConverter.java

Page 29: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-29

Retrieving and changing text in a component

• Components such as TextFields, Buttons, and Labels have methods to retrieve or modify their textgetText ( ) // retrieve text from objectsetText (“new text goes here”) // change text

• Examples:myLabel.setText (“you scored 93”);String name = nameTextField.getText ( );myButton.setText (“Erase”);

Page 30: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-30

Example

Resulting application window

This line is required to avoid a warning message

Proper way to start a simple GUI

application

Page 31: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-31

Handling Action Events

• An event is an action that takes place when the program is running, such as the user clicking of a button, moving a mouse, typing in a JTextField, etc.

• When an event takes place, the component that is responsible for the event creates an event object in memory

• The event object contains information about the event such as which component created the event and so forth

• The component that generated the event object is known as the event source

• It is possible that the event source component is connected to one or more event listeners

Page 32: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-32

Handling Action Events

• An event listener is an object that responds to specific events

• The source component fires an event which is passed to a method in the event listener

• Event listener classes are specific to each application

• Event listener classes are commonly written as private inner classes in an application

Page 33: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-33

Writing Event Listener Classes as Private Inner Classes

A class that is defined inside of another class is called an inner class

public class Outer{

Fields and methods of the Outer class appear here

private class Inner {

Fields and methods of the Inner class appear here }

}Private class Inner is only accessible and usable internally by its containing

class – Outer in this case

Page 34: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-34

UML – inner classes

Calculator class with 3 inner “listener” classes and a separate driver class

Connector for inner classes

Page 35: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-35

Event Listeners Must Implement an Interface

• All event listener classes must implement a specific interface

• Which interface it implements depends on the type of event for which it is listening

• Implementing the interface provides one or more method(s) to be executed if/when the specified event occurs

• This method takes the action appropriate for the program when that event happens

Page 36: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-36

Handling Action Events• JButton components generate action events,

which require an action listener class• Action listener classes may be named as you wish,

but each must meet the following requirements:It must implement the ActionListener interfaceIt must have a method named actionPerformed

• The actionPerformed method takes an argument of the ActionEvent typepublic void actionPerformed (ActionEvent e){ Code to be executed when button is pressed goes here

}

Page 37: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-37

Handling Action Events

JButton Component Action Listener Objectvoid actionPerformed(ActionEvent e)

When the button is pressed …

ActionEventObject

The JButton component generates an event object and passes it to the action listener

object's actionPerformed method

Examples: KiloConverterWindow.java, KilometerConverter.java

Page 38: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-38

Registering A Listener• The process of connecting an event listener

object to a component is called registering the event listener

• JButton components have a method named addActionListener

calcButton.addActionListener( new CalcButtonListener());

• When the user clicks on the source button, the action listener object’s actionPerformed method will be executed

Page 39: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-39

Background and Foreground Colors

• Many of the Swing component classes have methods named setBackground and setForeground

• setBackground is used to change the color of the component itself

• setForeground is used to change the color of the text displayed on the component

• Each method takes a color constant as an argument

Page 40: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-40

Color Constants• Predefined constants can be used to designate colors

Color.BLACK Color.BLUEColor.CYAN Color.DARK_GRAYColor.GRAY Color.GREENColor.LIGHT_GRAY Color.MAGENTAColor.ORANGE Color.PINKColor.RED Color.WHITEColor.YELLOW

• Examples: ColorWindow.java, ColorDemo.java

Page 41: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-41

Example: using colors

Continued …

Page 42: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-42

Example: colors, continued

Driver …

Page 43: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-43

Example, continued

Initial window

After clicking Red

After clicking Blue

After clicking Yellow

Page 44: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-44

The ActionEvent Object

• Event objects contain certain information about the event

• This information can be obtained by calling one of the event object’s methods

• Two of these methods are:getSource - returns a reference to the object that

generated this eventgetActionCommand - returns the action command for

this event as a String• Example:

EventObjectWindow.java, EventObjectDemo.java

Page 45: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-45

Layout Managers• An important part of designing a GUI application is

determining the layout of the components• The term layout refers to the positioning and

sizing of components• In Java, you do not normally specify the exact

location of a component within a window• A layout manager is an object that:

controls the positions and sizes of components

makes adjustments when necessary

Page 46: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-46

Layout Managers• The layout manager object and its container work

together• Java provides several layout managers. Three are:

FlowLayout - Arranges components in rows. This is the default for panels. If something will not fit on one row it moves to the next row

BorderLayout - Arranges components in five regions:North, South, East, West, and Center

This is the default layout manager for a JFrame object’s content pane

GridLayout - Arranges components in a grid with rows and columns

Page 47: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-47

Layout Managers• The Container class is one of the base classes

from which many components are derived• Any component that is derived from the Container class can have a layout manager added to it

• You add a layout manager to a container by calling the setLayout method

JPanel panel = new JPanel( );panel.setLayout(new BorderLayout( ));

• In a JFrame constructor you might use:setLayout(new FlowLayout( ));

Page 48: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-48

FlowLayout Manager

• FlowLayout is the default layout manager for JPanel objects

• Components appear horizontally, from left to right, in the order that they were added. When there is no more room in a row, the next components “flow” to the next row

• See example: FlowWindow.java

Page 49: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-49

Flow Layout Example

Initial Window

After stretching window horizontally

After resizing again

Page 50: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-50

FlowLayout Manager• The FlowLayout manager allows you to align

components:in the center of each rowalong the left or right edges of each row

• An overloaded constructor allows you to pass:FlowLayout.CENTERFlowLayout.LEFTFlowLayout.RIGHT

• Example:

setLayout(new FlowLayout(FlowLayout.LEFT));

Page 51: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-51

FlowLayout Manager• FlowLayout inserts a gap of five pixels between

components, horizontally and vertically by default• An overloaded FlowLayout constructor allows

these to be adjusted• The constructor has the following format:

FlowLayout(int alignment, int horizontalGap, int verticalGap)

• Example:

setLayout (new FlowLayout (FlowLayout.LEFT, 10, 7));

Page 52: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-52

BorderLayout ManagerThe BorderLayout manager manages five regions where

components can be placed

Page 53: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-53

BorderLayout Manager• See example: BorderWindow.java• A component placed into a container that is

managed by a BorderLayout must be placed into one of five regions:BorderLayout.NORTHBorderLayout.SOUTHBorderLayout.EASTBorderLayout.WESTBorderLayout.CENTER

Page 54: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-54

Border Layout Example

Page 55: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-55

BorderLayout Manager

• Each region can hold only one component at a timeThe component may, however, be a panel which itself holds

several components

• When a component is added to a region, it is stretched so it fills up the entire region – see previous example

• BorderLayout is the default manager for JFrame objects

add(button, BorderLayout.NORTH);

• If you do not pass a second argument to the add method, the component will be added to the center region

Page 56: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-56

BorderLayout Manager

• Normally a button is just large enough to accommodate the text that it displays

• The buttons displayed in BorderLayout region will not retain their normal sizeComponents are stretched to fill all of the space

in their regions

Page 57: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-57

BorderLayout Manager• If the user resizes the window, the sizes of the

components will be changed as well• BorderLayout manager resizes

components:placed in the north or south regions are resized

horizontally so they fill the entire region,placed in the east or west regions are resized

vertically so they fill the entire regionA component that is placed in the center region

may be resized both horizontally and vertically so it fills up the entire region

Page 58: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-58

BorderLayout Manager• By default, there is no gap between the

regions• An overloaded BorderLayout constructor

allows horizontal and vertical gaps to be specified (in pixels)

• The constructor has the following formatBorderLayout(int horizontalGap, int verticalGap)

• Example:setLayout(new BorderLayout(5,10));

Page 59: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-59

Nesting Components in a Layout

• Adding components to panels and then nesting the panels inside the regions can overcome the single component limitation of layout regions

• By adding buttons or other components to a JPanel and then adding the JPanel object to a region, sophisticated layouts can be achieved

• See example: next slide

Page 60: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-60

Border Layout Manager example

Page 61: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-61

GridLayout Manager

GridLayout creates a grid with rows and columns, much like a spreadsheet. A container that is managed by a

GridLayout object is divided into equally sized cells

columns

rows

Page 62: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-62

GridLayout Manager

• GridLayout manager follows some simple rules:Each cell can hold only one componentAll of the cells are the size of the largest

component placed within the layoutA component that is placed in a cell is

automatically resized to fill up any extra space• Pass the number of rows and columns as

arguments to the GridLayout constructor

Page 63: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-63

GridLayout Manager

• The general format of the constructor:GridLayout(int rows, int columns)

• ExamplesetLayout(new GridLayout(2, 3));

• A zero (0) can be passed for one of the arguments but not bothpassing 0 for both arguments will cause an IllegalArgumentException to be thrown

Page 64: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-64

GridLayout Manager

• Components are added to a GridLayout in the following order (for a 5×5 grid):

2524232221

2019181716

1514131211

109876

54321Example:

GridWindow.java

GridLayout also accepts nested components:

Example:GridPanelWindow.java

Page 65: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-65

Grid Layout Example

Page 66: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-66

Radio Buttons

• Radio buttons allow the user to select exactly one choice from several possible options

• The JRadioButton class is used to create radio buttons

• JRadioButton constructors: JRadioButton(String text) JRadioButton(String text, boolean selected)

• Example:JRadioButton radio1 = new JRadioButton("Choice 1");

orJRadioButton radio1 = new JRadioButton("Choice 1", true);

Button appears already selected

when true

Page 67: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-67

Button Groups• Radio buttons normally are grouped together• In a radio button group only one of the radio

buttons in the group may be selected at any time

• Clicking on a radio button selects it and automatically deselects any other radio button in the same group

• An instance of the ButtonGroup class is a used to group radio buttons

Page 68: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-68

Button Groups• The ButtonGroup object creates the mutually

exclusive relationship between the radio buttons that it contains. There is no visible representation of the ButtonGroup object – it is for internal use by the program JRadioButton radio1 = new JRadioButton("Choice 1", true);JRadioButton radio2 = new JRadioButton("Choice 2");JRadioButton radio3 = new JRadioButton("Choice 3");

ButtonGroup group = new ButtonGroup( );group.add (radio1);group.add (radio2);group.add (radio3);

Page 69: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-69

Button Groups

• ButtonGroup objects are not containers like JPanel objects or content frames

• If you wish to add the radio buttons to a panel or a content frame, you must add them individuallypanel.add(radio1);panel.add(radio2);panel.add(radio3);

Page 70: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-70

Radio Button Events

• JRadioButton objects generate an action event when they are clicked

• To respond to an action event, you must write an ActionListener class, just like a JButton event handler

• See example: MetricConverter.java

Page 71: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-71

Example

Continued …

Page 72: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-72

Example, continued

Page 73: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-73

Determining Selected Radio Buttons

• The JRadioButton class’s isSelected method returns a boolean value indicating if the radio button is selected

if (radioButton1.isSelected()){ // This code executes if radioButton1 selected}

Page 74: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-74

Selecting a Radio Button in Code

• It is also possible to select a radio button programmatically in your code with the JRadioButton class’s doClick method

• When the method is called, the radio button is selected just as if the user had clicked on it

• As a result, an action event is generatedradio.doClick( );

Page 75: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-75

Check Boxes

• A check box appears as a small box with a label appearing next to it

• Like radio buttons, check boxes may be selected or deselected at run time

• When a check box is selected, a small check mark appears inside the box

• Check boxes are often displayed in groups but they are not usually grouped into a ButtonGroup

Page 76: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-76

Check Boxes• The user is allowed to select any or all of the check

boxes that are displayed in a group• The JCheckBox class is used to create check box

objects• Two JCheckBox constructors:

JCheckBox (String text)JCheckBox (String text, boolean selected)

• Examples:JCheckBox check1 = new JCheckBox("Macaroni");JCheckBox check1 = new JCheckBox("Macaroni", true);

Check appears in box if true

Page 77: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-77

Check Box Events• When a JCheckBox object is selected or

deselected, it generates an item event• Handling item events is similar to handling action

events• Write an item listener class, which must meet the

following requirements:It must implement the ItemListener interfaceIt must have a method named itemStateChanged

This method must take an argument of the ItemEvent type

Page 78: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-78

Check Box Events

• Create an object of the class• Register the item listener object with the JCheckBox component

• On an event, the itemStateChanged method of the item listener object is automatically runThe event object is passed in as an argument

Page 79: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-79

Determining Selected Check Boxes

• The isSelected method will determine whether a JCheckBox component is selected

• The method returns a boolean valueif (checkBox.isSelected( )){ // Code here executes only if the check // box is selected}

• One may use the SetSelected method to programmatically check/uncheck a checkbox

myCheckBox.SetSelected (true);

• See example: ColorCheckBoxWindow.java

Page 80: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-80

Selecting Check Boxes in Code

• It is possible to select check boxes programmatically in code with the JCheckBox class’s doClick method

• When the method is called, the check box is selected just as if the user had clicked on it

• As a result, an item event is generatedcheckBox.doClick();

Page 81: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-81

BORDERS

Adding borders can improve the window appearance and/or the logical groupings of some of its controls

Page 82: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-82

Borders• Windows have a more organized look if related

components are grouped inside borders

• You can add a border to any component that is derived from the JComponent classEvery component derived from JComponent inherits a

method named setBorder

Page 83: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-83

Borders• The setBorder method is used to add a

border to the component• The setBorder method accepts a Border

object as its argument• A Border object contains detailed information

describing the appearance of a border• The BorderFactory class, which is part of

the javax.swing package, has static methods that return various types of borders

Page 84: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-84

Border BorderFactory Method Description

Compound border createCompoundBorder

A border that has two parts: an inside edge and an outside edge. The inside and outside edges can be any of the other borders.

Empty border createEmptyBorder A border that contains only empty space.

Etched border createEtchedBorder A border with a 3D appearance that looks “etched” into the background.

Line border createLineBorder A border that appears as a line.

Lowered bevel border createLoweredBevelBorder

A border that looks like beveled edges. It has a 3D appearance that gives the illusion of being sunken into the surrounding background.

Matte border createMatteBorder A line border that can have edges of different thicknesses.

Raised bevel border

createRaisedBevelBorderA border that looks like beveled edges. It has a 3D appearance that gives the illusion of being raised above the surrounding background.

Titled border createTitledBorder An etched border with a title.

Page 85: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-85

Examples of Creating a Border

Page 86: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-89

Short topics

• One may control the placement of a new window by setting its location relative to another component using JFrame’s setLocationRelativeTo methodsetLocationRelativeTo (component);If component is null, the JFrame object is centered on the screen

Make sure the JFrame object is sized correctly before setting its location – otherwise the location will not be calculated properly

Page 87: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-90

Short topics - continued• If a JFrame has one or more buttons in its content

pane, one may be designated as the default buttonA default button is “activated” – causes a click event to

be generated – when the <ENTER> key is pressedUse getRootPane ( ).setDefaultButton to set the default

button

// sets btnCalc as the default buttongetRootPane ( ).setDefaultButton (btnCalc);

Set as Default button

Page 88: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-91

Short topics - continued• A control is said to “have the focus” if a character typed at the

keyboard will be sent to that control A text field with the focus is where the next text typed will appear A user may give the focus to a control by clicking on it with the

mouse (assuming the control can “have” the focus)

One may also programmatically assign the focus by using the control’s grabFocus method

This is useful to allow user to begin typing immediately instead of having to click on the text field first Note the cursor

has been placed in the textbox and the

text has been selected. What the user types replaces

the “1” instead of adding other

characters to it

Page 89: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-92

Focus Events• One may handle events related to a text field getting the

focus or losing the focus. For example, one may wish toSelect all of the text in a field when it receives the focusUse the value in the field when leaving it

• These events are handled with a private inner class that implements the FocusListener interface that requires one to implement both focusGained and focusLost methods

• Use addFocusListener to register the event handler for the text field

Page 90: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-93

Focus Event listener example

Page 91: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-94

Short Topics - continued

• It is good practice and more professional looking to right-justify numbers in text-fieldsThis can be done by changing the default left-

justification using a command like the following for a text field named myTF:myTF.setHorizontalAlignment (JTextField.RIGHT);

Do this only for numeric fields. Ordinary text should be left-justified (the default in our culture)

Page 92: Starting Out with Java:  Early  Objects  Third Edition by Tony  Gaddis as modified for CSCI 1260

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-95

Short topics, continued• Following are some useful methods with JFrames

setResizable (boolean b) allows or prohibits the user from resizing the JFrame by dragging the frame or using the maximize button

dispose ( ) releases all of the native screen resources used by this window, its subcomponents, and all of its owned children. The resources will be destroyed and any memory used will be returned to the OS for other use; often used when one JFrame has opened another JFrame or JDialog, and the second one should now be destroyed without closing the application

pack ( ) causes this window to be sized to fit the preferred size and layouts of its subcomponents; used as an alternative to setting the size manually; should be used only after all subcomponents have been added and their properties set