graphical user interface

58
Graphical User Interface Chapter 7

Upload: brianna-kirby

Post on 30-Dec-2015

53 views

Category:

Documents


0 download

DESCRIPTION

Graphical User Interface. Chapter 7. Java Foundation Classes. Use the Java Foundation Classes (JFC) to create a graphical user interface for your application. Two sets of JFC classes AWT (Abstract Windowing toolkit) Directs the underlying OS to draw its own built-in components - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Graphical User Interface

Graphical User Interface

Chapter 7

Page 2: Graphical User Interface

Java Foundation Classes• Use the Java Foundation Classes (JFC) to create

a graphical user interface for your application.• Two sets of JFC classes

– AWT (Abstract Windowing toolkit)• Directs the underlying OS to draw its own built-in

components

import java.awt.*; // BorderLayout, GridLayout

– Swing : • Draws most of its components on the screen

import javax.swing.*;

Page 3: Graphical User Interface

Package: javax.swing• In this chapter we will use the following Swing

classes– JOptionPane – JFrame – JPanel– JLabel– JTextField– JButton– JCheckBox – JRadioButton– BorderFactory

Page 4: Graphical User Interface

Frame

• A basic window that has a border around it, title bar, and a set of buttons for minimizing, maximizing and closing the window

• Create a frame object with the JFrame class (a Swing class)

Page 5: Graphical User Interface

Methods in JFrame• Import JFrame class

import javax.swing.JFrame;import javax.swing.*;

• Set Original Size of WindowsetSize (300,200) // width, height in pixels

• Set Title of WindowsetTitle (“Window Title”);

Page 6: Graphical User Interface

Methods in JFrame (Cont)• Specify Closing OptionsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

– HIDE_ON_CLOSE• The window is hidden from view, but the application

does not end.• This is the default action

– EXIT_ON_CLOSE• Ends application with a System.exit call

• Make the window visiblesetVisible ( true );– A JFrame is initially invisible.

Page 7: Graphical User Interface

Extending the JFrame Classimport javax.swing.*;public class ShowWindow2 extends JFrame{ public ShowWindow2() {

setTitle(“Show Window 2”); setSize(250,150); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); }

public static void main (String[] args){

ShowWindow2 app = new ShowWindow2();}

}

Embedded main

Create new specialized class that Inherits from JFrame

constructor

Page 8: Graphical User Interface

Adding Components

• Swing provides numerous components that can be added to a window.

• Three fundamental components 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.

Page 9: Graphical User Interface

Sketch of Kilometer Converter Graphical User Interface

Window Title

Label

Button

Text Field

Page 10: Graphical User Interface

Declare GUI Components

• This code declares and instantiates three Swing components.

//Declare Components as Instance Fieldsprivate JLabel message;private JTextField kilometers;private JButton calcButton;…

//Instantiate the components within the constructormessage = new Jlabel("Enter a distance in kilometers");kilometers = new JTextField(10);calcButton = new JButton("Calculate");

Page 11: Graphical User Interface

Making the Components Visible

• 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 also a container that can hold GUI components.

Page 12: Graphical User Interface

Adding Components to Panel• Panels cannot be displayed by themselves.

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

• Create panels with the JPanel class.private JPanel panel;

panel = new JPanel();

panel.add(message);

panel.add(kilometers);

panel.add(calcButton);

• Add Panel to JFrameadd(panel);

Page 13: Graphical User Interface

Review of Adding Components

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

1) Create a JPanel

2) Add GUI Components to JPanel

3) Add JPanel to JFrame

Page 14: Graphical User Interface

Handling Action Events• An event is an action that takes place within a

program, such as the clicking of a button.• 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.

• The component that generated the event object is know as the event source.

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

Page 15: Graphical User Interface

Handling Action Events• An event listener is an object that responds

to 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 16: Graphical User Interface

Event Listeners Must Implement an Interface

• All event listener classes must implement an interface.

• An interface is something like a class containing one or more method headers.

• When you write a class that implements an interface, you are agreeing that the class will have all of the methods that are specified in the interface.

Page 17: Graphical User Interface

Handling Action Events• JButton components generate action events,

which require an action listener class.• Action listener classes must meet the following

requirements:– It must implement the ActionListener interface.– It must have a method named actionPerformed.

• The actionPerformed method takes an argument of the ActionEvent type.public void actionPerformed(ActionEvent e){

Code to be executed when button is pressed goes here.}

Page 18: Graphical User Interface

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 19: Graphical User Interface

7-19

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 20: Graphical User Interface

7-20

Color Constants• There are predefined constants that you can

use for colors.Color.BLACK Color.BLUE

Color.CYAN Color.DARK_GRAY

Color.GRAY Color.GREEN

Color.LIGHT_GRAY Color.MAGENTA

Color.ORANGE Color.PINK

Color.RED Color.WHITE

Color.YELLOW

JTextField msg= new JTextField(“hello world”);msg.setForeground(Color.BLUE);msg.setBackground(Color.YELLOW);

hello world

Page 21: Graphical User Interface

Create New Colors

• new Color(R, G, B )

RGB & Hex Values

http://cloford.com/resources/colours/500col.htmColor

Combohttp://www.colorcombos.com/color-schemes/428/ColorCombo428.html

Page 22: Graphical User Interface

7-22

The ActionEvent Object• Event objects contain certain information about the

event. getSource - returns a reference to the object that generated

this event.getActionCommand - returns the action command for this

event as a String.

public void actionPerformed(ActionEvent e){ if (e.getSource() == greenButton)

colorPanel.setBackground(Color.GREEN); if (e.getSource() == redButton)

colorPanel.setBackground(Color.RED); msg.setText(e.getActionCommand()); }

Page 23: Graphical User Interface

Layout ManagersArrange GUI components in a container

• FlowLayout– Default for JPanel– Places components sequentially (left to right) in the

order they were added

• BorderLayout– Default for JFrame and JApplet– Arranges components into 5 areas: NORTH, SOUTH,

EAST, WEST, CENTER– If area is not specified CENTER is assumed

• GridLayout– Arranges components into rows and columns

Page 24: Graphical User Interface

7-24

Setting Layout Managers

• The Container class is one of the base classes that many components are derived from.

• 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 25: Graphical User Interface

FlowLayout• Simplest layout manager• Places components sequentially in the order they

were added• Objects wrap to the next line when edge of

container is reached.

Page 26: Graphical User Interface

FlowLayout (cont)

•Default alignment is CENTER•Use method setAlignment to change the alignment

Page 27: Graphical User Interface

BorderLayout• Default for JFrame and JApplet• Arranges components into 5 areas: NORTH, SOUTH,

EAST, WEST, CENTER• The constructor can specify the number of horizontal and

vertical pixel gaps: new BorderLayout(5,5);

Page 28: Graphical User Interface

BorderLayout(cont)

• If area is not specified CENTER is assumed• Only one GUI object per area (however you can

add containers)

Page 29: Graphical User Interface

GridLayout• Arranges components into rows and columns• Components are added starting at the top-left cell and

proceeding left to right until the row is full.• The constructor can specify the number of horizontal and

vertical pixel gaps: new GridLayout(2,3,5,5);

Page 30: Graphical User Interface

GridLayout• Arranges components into rows and columns• Components are added starting at the top-left cell and

proceeding left to right until the row is full.• The constructor can specify the number of horizontal and

vertical pixel gaps: new GridLayout(2,3,5,5);

Page 31: Graphical User Interface

GridBagLayout• Places components in a grid of rows and columns, allowing

specified components to span multiple rows or columns.• GridBagLayout places components in rectangles (cells) in a

grid, and then uses the components' preferred sizes to determine how big the cells should be.

Page 32: Graphical User Interface

GridBagLayout

Page 33: Graphical User Interface

GridBagLayoutConstraints• gridx, gridy - specify the row and column• gridwidth, gridheight -Specify the number of columns (for gridwidth) or rows (for gridheight) in the component's

display area. • Fill - Used when the component's display area is larger than the component's requested size to determine whether

and how to resize the component. NONE (the default,) HORIZONTAL, VERTICAL, BOTH, • ipadx, ipady - Specifies the internal padding: how much to add to the size of the component. The default value is

zero. • Insets - Specifies the external padding of the component -- the minimum amount of space between the component

and the edges of its display area.

Page 34: Graphical User Interface

GridBagLayoutConstraints• Anchor - Used when the component is smaller than its display area to determine where (within the area)

to place the component. FIRST_LINE_START PAGE_START FIRST_LINE_END

LINE_START CENTER LINE_END

LAST_LINE_START PAGE_END LAST_LINE_END

• weightx, weighty -Weights are used to determine how to distribute space among columns (weightx) and among rows (weighty)–Unless you specify at least one non-zero value for weightx or weighty, all the components clump together in the center of their container

Page 35: Graphical User Interface

JPanel

• Complex user interfaces often consist of multiple panels that contain a collection of GUI objects.

• Every JPanel is a container, so it may have components, including other panels added to them.

Page 36: Graphical User Interface

JTabbedPane• Manage two or more JPanels that share the same display

space. .

Page 37: Graphical User Interface

Setting Layout Managers• Each container can have only one layout manager

at a time. • Separate containers in the same program can

have different layouts. • Normally, the layout is set before any GUI

components are added.• To realign attached components use layoutContainer() or validate() methods

Page 38: Graphical User Interface

Reformatting Container

Page 39: Graphical User Interface

7-39

Radio Buttons• Radio buttons allow the user to select 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 40: Graphical User Interface

7-40

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 41: Graphical User Interface

7-41

Button Groups

• The ButtonGroup object creates the mutually exclusive relationship between the radio buttons that it contains.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 42: Graphical User Interface

7-42

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 individually.panel.add(radio1);

panel.add(radio2);

panel.add(radio3);

Page 43: Graphical User Interface

7-43

Radio Button Events

• JRadioButton objects generate an action event when they are clicked.

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

• See example: MetricConverterWindow.java

Page 44: Graphical User Interface

7-44

Determining Selected Radio Buttons

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

{

// Code here executes if the radio

// button is selected.

}

Page 45: Graphical User Interface

7-45

Selecting a Radio Button in Code

• It is also possible to select a radio button in 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 generated.radio.doClick();

Page 46: Graphical User Interface

7-46

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 in a ButtonGroup.

Page 47: Graphical User Interface

7-47

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 boxes.• Two JCheckBox constructors:

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

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

Check appears in box if true

Page 48: Graphical User Interface

7-48

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 interface.– It must have a method named itemStateChanged.

• This method must take an argument of the ItemEvent type.

Page 49: Graphical User Interface

7-49

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 run– The event object is passed in as an argument.

Page 50: Graphical User Interface

7-50

Determining Selected Check Boxes

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

• The method returns a boolean value. if (checkBox.isSelected())

{

// Code here executes if the check

// box is selected.

}

• See example: ColorCheckBoxWindow.java

Page 51: Graphical User Interface

7-51

Selecting Check Boxes in Code

• It is possible to select check boxes 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 generated.checkBox.doClick();

Page 52: Graphical User Interface

7-52

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 class.– Any component derived from JComponent

inherits a method named setBorder

Page 53: Graphical User Interface

7-53

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 54: Graphical User Interface

7-54

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 createEtchedBorderA 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 createMatteBorderA line border that can have edges of different thicknesses.

Raised bevel border

createRaisedBevelBorder

A 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 55: Graphical User Interface

7-55

The Brandi’s Bagel House Application

• A complex application that uses numeroous components can be constructed from several specialized panel components, each containing other components and related code such as event listeners.

• Examples:

GreetingPanel.java, BagelPanel.java, ToppingPanel.java, CoffeePanel.java,OrderCalculatorGUI.java, Bagel.java

Page 56: Graphical User Interface

7-56

Splash Screens

• A splash screen is a graphic image that is displayed while an application loads into memory and starts up.

• A splash screen keeps the user's attention while a large application loads and executes.

• Beginning with Java 6, you can display splash screens with your Java applications.

Page 57: Graphical User Interface

7-57

Splash Screens

• To display the splash screen you use the java command in the following way when you run the application:

java -splash:GraphicFileName ClassFileName

• GraphicFileName is the name of the file that contains the graphic image, and ClassFileName is the name of the .class fi le that you are running.

• The graphic file can be in the GIF, PNG, or JPEG formats.

Page 58: Graphical User Interface

7-58

Using Console Output to Debug a GUI

• Display variable values, etc. as your application executes to identify logic errors– Use System.out.println()

// For debugging, display the text entered, and// its value converted to a double. System.out.println("Reading " + str +

" from the text field."); System.out.println("Converted value: " + Double.parseDouble(str));

• See example: KiloConverterWindow.java