51
Course Briefing

Chapter 1 Intro to GUI - Part 1.pptx

Embed Size (px)

Citation preview

Course Briefing

Refer to:

• Course Information for Students

2

• NetBeans IDE Java Quick Start Tutorial

3

GUI Components – Part 1

Chapter 1

Lesson Objectives

At the end of this lesson, you should be able to• Create a simple application using dialog boxes.• Describe what are components and containers in a

graphical user interface.• Create a GUI application class by extending the JFrame class.

5

• A graphical user interface (GUI) makes a system user-friendly and easy to use.

Introduction

6

Dialog Boxes

• Also known as dialogs.• Windows in which programs display important

messages to the user or obtain information from the user.

• Java’s javax.swing.JOptionPane class provides pre-built dialog boxes for input and output.

7

A. Create a new NetBeans project named Chapter1Uncheck the Create Main Class checkbox.

B. Create a new Java Main Class named AdditionStep 1. Choose File Type Categories: Java, Files Types: Java Main ClassStep 2. Name and Location Class Name: Addition

8

import javax.swing.JOptionPane;

public class Addition {

public static void main(String[] args) {

String firstNumber = JOptionPane.showInputDialog("Enter first integer");

String secondNumber = JOptionPane.showInputDialog("Enter second integer");

int firstInt = Integer.parseInt(firstNumber);

int secondInt = Integer.parseInt(secondNumber);

int sum = firstInt + secondInt;

JOptionPane.showMessageDialog(null, "The sum is " + sum);

}

} 9

JOptionPane DialogsA dialog is normally used as a temporary window to receive additional information from the user, or to provide notification that some event has occurred.

A JOptionPane dialog can display

an icon, a message, an input, and option

buttons.

10

Message DialogsA message dialog box simply displays a message to alert the user and waits for the user to click the OK button to close the dialog.

JOptionPane.showMessageDialog(null, “This is an error",

“Error", JOptionPane.INFORMATION_MESSAGE);

11

Message Types

The messageType is one of the following constants:JOptionPane.ERROR_MESSAGEJOptionPane.INFORMATION_MESSAGE JOptionPane.PLAIN_MESSAGEJOptionPane.WARNING_MESSAGEJOptionPane.QUESTION_MESSAGE

Input DialogsAn input dialog box is used to receive input from the user.

13

Confirmation Dialogs

A message dialog box displays a message and waits for the user to click the OK button to dismiss the dialog. The message dialog does not return any value. A confirmation dialog asks a question and requires the user to respond with an appropriate button. The confirmation dialog returns a value that corresponds to a selected button.

14

Good UI Design

• Consistency. – Consistent user interfaces enable a user to learn

new applications faster.– Use sentence-style capitalization for prompts in an

input dialog.– Use book-title capitalization for the title bar of a

window.

15

P1 Q1

16

Modal Dialog

• Each JOptionPane dialog that you display is a modal dialog – while the dialog is on the screen, the user cannot interact with the rest of the application.

• Do not overuse modal dialogs as they can reduce the usability of your applications. Use them only when it’s necessary to prevent users from interacting with the rest of the application until they dismiss the dialog.

17

• GUIs are built from GUI components.

• Creating a GUI requires creativity and knowledge of how GUI components work.

Introduction to GUI Components

18

GUI Components• A.k.a. controls or widgets (window gadgets). Frames Windows that can include a title bar, menu bar and

Maximize, Minimize, and Close buttons.Containers Interface elements that can hold other components.

Buttons Clickable regions with text or graphics indicating their purpose.

Labels Text or graphics that provide information.

Text fields Text areas

Windows that accept keyboard input and allow text to be edited.

Drop-down lists

Groups of related items that can be selected from drop-down menus or scrolling windows.

Check boxesRadio buttons

Small boxes or circles that can be selected or deselected.

19

Coming up next

• The following section provides a brief overview of the Java GUI API.

• A detailed coverage will be covered much later.

20

Packages for GUI ProgrammingPackage Type of Classes

javax.swing GUI components such as labels, text fields, buttons, etc. When you use a Swing component, you work with objects of that component’s class. You create the component by calling its constructor and then call methods of the component as needed for proper setup.

java.awt The Abstract Windowing Toolkit

java.awt.event Event-handling classes that handle user input.

21

The Java GUI API – 3 groups

• Component classes

• Container classes

• Helper classes

• 22

Swing Components

• All Swing components are subclasses of the abstract class JComponent.

• Jcomponent include methods too Set the size of a componento Change the background coloro Define the font used for any displayed texto Set up ToolTips – explanatory text that appears

when the mouse pointer is over the component.

23

GUI Class Hierarchy

Dimension

Font

FontMetrics

Component

Graphics

Object Color

Container

Panel Applet

Frame

Dialog

Window

JComponent

JApplet

JFrame

JDialog

Swing Components in the javax.swing package

Lightweight

Heavyweight

Classes in the java.awt package

1

LayoutManager

*

24

Component Classes

• An instance of Component can be displayed on the screen.

25

Swing GUI Components

JMenuItem

JCheckBoxMenuItem

AbstractButton

JComponent

JMenu

JRadioButtonMenuItem

JToggleButton JCheckBox

JRadioButton

JComboBox

JInternalFrame

JLayeredPane

JList

JMenuBar

JOptionPane

JPopupMenu

JProgressBar

JFileChooser

JScrollBar

JScrollPane JSeparator JSplitPane

JSlider

JTabbedPane

JTable JTableHeader

JTextField JTextComponent

JTextArea

JToolBar JToolTip

JTree

JRootPane

JPanel

JPasswordField

JColorChooser

JLabel

JEditorPane

JSpinner

JButton

26

Common Features of Swing Components

java.awt.Container

+add(comp: Component): Component

+add(comp: Component, index: int): Component

+remove(comp: Component): void

+getLayout(): LayoutManager

+setLayout(l: LayoutManager): void

+paintComponents(g: Graphics): void

Adds a component to the container.

Adds a component to the container with the specified index.

Removes the component from the container.

Returns the layout manager for this container.

Sets the layout manager for this container.

Paints each of the components in this container.

java.awt.Component

-font: java.awt.Font

-background: java.awt.Color

-foreground: java.awt.Color

-preferredSize: Dimension

-visible: boolean

+getWidth(): int

+getHeight(): int

+getX(): int

+getY(): int

The font of this component.

The background color of this component.

The foreground color of this component.

The preferred size of this component.

Indicates whether this component is visible.

Returns the width of this component.

Returns the height of this component.

getX() and getY() return the coordinate of the component’s upper-left corner within its parent component.

javax.swing.JComponent

-toolTipText: String

-border: javax.swing.border.Border

The tool tip text for this component. Tool tip text is displayed when the mouse points on the component without clicking.

The border for this component.

The get and set methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.

The get and set methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.

27

Creating GUI Objects// Create a button with text OK JButton jbtOK = new JButton("OK");  // Create a label with text "Enter your name: "JLabel jlblName = new JLabel("Enter your name: ");  

// Create a text field with text "Type Name Here"JTextField jtfName = new JTextField("Type Name Here");  // Create a check box with text boldJCheckBox jchkBold = new JCheckBox("Bold");  // Create a radio button with text redJRadioButton jrbRed = new JRadioButton("Red");  // Create a combo box with choices red, green, and blueJComboBox jcboColor = new JComboBox(new String[]{"Red”,"Green", "Blue"});

Button

Label Text field

Check Box

Radio Button

Combo Box

28

Container Classes

• An instance of Container can hold instances of Component.

29

Container Classes

Dimension

Font

FontMetrics

Component

Graphics

Object Color

Container

Panel Applet

Frame

Dialog

Window

JComponent

JApplet

JFrame

JDialog

Swing Components in the javax.swing package

Lightweight

Heavyweight

Classes in the java.awt package

1

LayoutManager

*

JPanel

30

GUI Container ClassesContainer Class Description

java.awt.Container Used to group components. Frames, panels, and applets are its subclasses.

javax.swing.JFrame A window not contained inside another window. Used to hold other GUI components.

javax.swing.JPanel An invisible container that holds UI components. Panels can be nested.

javax.swing.JApplet A base class for creating a Java applet.

javax.swing.JDialog A popup window or message box used as a temporary window to receive additional info or provide notification that an event has occurred.

31

GUI Helper Classes

Dimension

Font

FontMetrics

Component

Graphics

Object Color

Container

Panel Applet

Frame

Dialog

Window

JComponent

JApplet

JFrame

JDialog

Swing Components in the javax.swing package

Lightweight

Heavyweight

Classes in the java.awt package

1

LayoutManager

*

JPanel The helper classes are not subclasses of Component. They are used to describe the properties of GUI components such as graphics context, colors, fonts, and dimension. 32

Some GUI Helper ClassesContainer Class Description

java.awt.Color Deals with colors of GUI components, e.g. to specify background or foreground colors.

java.awt.Font Specifies fonts for the text.

java.awt.FontMetrics An abstract class used to get the properties of the fonts.

java.awt.Dimension Encapsulates the width and height of a component in a single object.

java.awt.LayoutManager Specifies how components are arranged in a container

33

Review: What Am I?

1. An object that can be displayed on the screen. A component

2. An object that holds instances of Component. A cointainer

34

Review

1. The GUI API classes may be classified into 3 groups. What are the 3 groups? Component classes

Container classes

Helper classes

35

Creating a User Interface

• The first step in creating a GUI application is to create a class that represents the graphical user interface. An object of this class serves as a container that holds the components to be displayed. You need to create a frame to hold the GUI components.

The next section introduces frames.

36

Frames

• A window for holding other GUI components. It is a window that is not contained inside another window.

• To create a frame, use the JFrame.

37

JFrame Class javax.swing.JFrame

+JFrame()

+JFrame(title: String)

+setSize(width: int, height: int): void

+setLocation(x: int, y: int): void

+setVisible(visible: boolean): void

+setDefaultCloseOperation(mode: int): void

+setLocationRelativeTo(c: Component): void

+pack(): void

Creates a default frame with no title.

Creates a frame with the specified title.

Specifies the size of the frame.

Specifies the upper-left corner location of the frame.

Sets true to display the frame.

Specifies the operation when the frame is closed.

Sets the location of the frame relative to the specified component. If the component is null, the frame is centered on the screen.

Automatically sets the frame size to hold the components in the frame.

JFrame is a top-level container to hold GUI components

38

39

A. Open your Chapter1 NetBeans project

B. Create a new Java Main Class named MyFrameStep 1. Choose File Type Categories: Java, Files Types: Java Main ClassStep 2. Name and Location Class Name: MyFrame

import javax.swing.JOptionPane;

public class MyFrame extends JFrame {

public MyFrame() {

super("Frame Title");

setSize(400, 300);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLocationRelativeTo(null);

setVisible(true);

}

public static void main(String[] args) {

MyFrame myFrame = new MyFrame();

}

}40

Method: Creating a Swing application

• Make the user interface a subclass of JFrame.

• The constructor of the class should include the following tasks:

1. Call a superclass constructor to give the frame a title and handle other setup procedures.

2. Set the size of the frame’s window.3. Specify what to do if a user closes the window.4. Display the frame.

41

JFrame Class javax.swing.JFrame

+JFrame()

+JFrame(title: String)

+setSize(width: int, height: int): void

+setLocation(x: int, y: int): void

+setVisible(visible: boolean): void

+setDefaultCloseOperation(mode: int): void

+setLocationRelativeTo(c: Component): void

+pack(): void

Creates a default frame with no title.

Creates a frame with the specified title.

Specifies the size of the frame.

Specifies the upper-left corner location of the frame.

Sets true to display the frame.

Specifies the operation when the frame is closed.

Sets the location of the frame relative to the specified component. If the component is null, the frame is centered on the screen.

Automatically sets the frame size to hold the components in the frame.

JFrame is a top-level container to hold GUI components

42

JFrame constants for setDefaultCloseOperation()’s

argumentsEXIT_ON_CLOSE Exit the application when the frame is

closed.

DISPOSE_ON_CLOSE Close the frame, remove the frame object from memory, and keep running the application.

DO_NOTHING_ON_CLOSE Keep the frame open and continue running.

HIDE_ON_CLOSE Close the frame and continue running.

43

The Frame’s Constructor

• The work involved in creating the frame’s user interface takes place in its constructor. When components are created and added to this frame, it is done within this constructor.

44

Creating a Component

• Each GUI component is represented by its own class. To create an GUI component in Java, you create an object of that component’s class.– E.g., to create a button, just create an instance of JButton.

45

46

To your MyFrame class• Add a button object

import javax.swing.JButton;import javax.swing.JOptionPane;

public class MyFrame extends JFrame {private JButton jbtOK = new JButton("OK");

public MyFrame() {

super("Frame Title"); add(jbtOK);

. . . } . . .}

47

JButton Constructors

The following are JButton constructors:

JButton()

JButton(String text)

JButton(String text, Icon icon)

JButton(Icon icon)

• 48

Adding Components to a Container

To add a component to a container, call the container’s add(Component) method with the component as the argument (all GUI components in Swing inherit from java.awt.Component).

• 49

P1 Q2

50

Review of Lesson Objectives

You should now be able to:• Create a simple application using dialog boxes.• Describe what are components and containers in a

graphical user interface.• Create a GUI application class by extending the JFrame class.