Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 51

Course Briefing

Refer to:
Course Information for Students

NetBeans IDE Java Quick Start


Tutorial

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.

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

Dialog Boxes
Also known as dialogs.
Windows in which programs display
important messages to the user or
obtain information from the user.
Javas javax.swing.JOptionPane
class provides pre-built dialog boxes
for input and output.

A. Create a new NetBeans project named Chapter1


Uncheck the Create Main Class checkbox.

B. Create a new Java Main Class named Addition


Step 1. Choose File Type
Categories: Java, Files Types: Java Main
Class
Step 2. Name and Location
Class Name: Addition

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 Dialogs
A 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 Dialogs
A 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_MESSAGE
JOptionPane.INFORMATION_MESSAGE
JOptionPane.PLAIN_MESSAGE
JOptionPane.WARNING_MESSAGE
JOptionPane.QUESTION_MESSAGE

Input Dialogs
An 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 its necessary to
prevent users from interacting with the
rest of the application until they dismiss
the dialog.
17

Introduction to GUI
Components

GUIs are built from GUI components.

Creating a GUI requires creativity


and
knowledge
of
how
GUI
components work.

18

GUI Components
A.k.a. controls or widgets (window
Frames
gadgets).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 Windows that accept keyboard input and
Text areas allow text to be edited.
Drop-down Groups of related items that can be
lists
selected from drop-down menus or scrolling
windows.
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


Programming

Package
javax.swing

java.awt
java.awt.event

Type of Classes
GUI components such as labels, text
fields, buttons, etc. When you use a
Swing component, you work with
objects of that components class. You
create the component by calling its
constructor and then call methods of
the component as needed for proper
setup.
The Abstract Windowing Toolkit
Event-handling classes that handle
user input.
21

The Java GUI API 3


groups

Compone
nt classes

Container
classes

Helper
classes

22

Swing Components
All Swing components are subclasses
of the abstract class JComponent.
Jcomponent include methods to
o Set the size of a component
o Change the background color
o Define the font used for any displayed text
o Set up ToolTips explanatory text that
appears when the mouse pointer is over
the component.
23

GUI Class Hierarchy


Dimension
Font

Classes in the java.awt


package

LayoutManager
1

Heavyweight

FontMetrics
Object

Color

Panel

Applet

JApplet

Window

Frame

JFrame

Dialog

JDialog

Graphics
Component

Container

Swing Components
in the javax.swing package

JComponent

Lightweight

24

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

25

Swing GUI Components


JCheckBoxMenuItem

AbstractButton

JComponent

JMenuItem

JMenu

JButton

JRadioButtonMenuItem

JToggleButton

JCheckBox
JRadioButton

JEditorPane
JTextComponent

JTextField

JPasswordField

JTextArea

JLabel

JTabbedPane
JToolBar
JTree

JComboBox

JList

JSplitPane
JMenuBar

JTable

JPanel

JLayeredPane
JPopupMenu

JTableHeader

JOptionPane
JSeparator
JFileChooser

JInternalFrame

JScrollBar

JSlider

JScrollPane

JRootPane

JColorChooser
JProgressBar
26

JToolTip

JSpinner

Common Features of Swing Components


java.awt.Component

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

-font: java.awt.Font

The font of this component.

-background: java.awt.Color

The background color of this component.

-foreground: java.awt.Color

The foreground color of this component.

-preferredSize: Dimension

The preferred size of this component.

-visible: boolean

Indicates whether this component is visible.

+getWidth(): int

Returns the width of this component.

+getHeight(): int

Returns the height of this component.

+getX(): int

getX() and getY() return the coordinate of the components


upper-left corner within its parent component.

+getY(): int

java.awt.Container
+add(comp: Component): Component

Adds a component to the container.

+add(comp: Component, index: int): Component Adds a component to the container with the specified index.
Removes the component from the container.
+remove(comp: Component): void
+getLayout(): LayoutManager

Returns the layout manager for this container.

+setLayout(l: LayoutManager): void

Sets the layout manager for this container.

+paintComponents(g: Graphics): void

Paints each of the components in this container.

javax.swing.JComponent

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

-toolTipText: String

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

-border: javax.swing.border.Border

The border for this component.

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: ");

Label

Text Check
field Box

Radio
Button

Button

// Create a text field with text "Type Name Here"


JTextField jtfName = new JTextField("Type Name Here");

Combo
Box

// Create a check box with text bold


JCheckBox jchkBold = new JCheckBox("Bold");
// Create a radio button with text red
JRadioButton jrbRed = new JRadioButton("Red");
// Create a combo box with choices red, green, and blue
JComboBox jcboColor = new JComboBox(new String[]{"Red,"Green", "Blue"});
28

Container Classes
An instance of Container can hold
instances of Component.

29

Container Classes
Dimension
Font

Classes in the java.awt


package

LayoutManager
1

Heavyweight

FontMetrics
Object

Color

Panel

Applet

JApplet

Window

Frame

JFrame

Dialog

JDialog

Graphics
Component

Container

JComponent

Swing Components
in the javax.swing package

JPanel

Lightweight

30

GUI Container Classes


Container Class
java.awt.Container

javax.swing.JFrame

javax.swing.JPanel

javax.swing.JApplet
javax.swing.JDialog

Description
Used to group components.
Frames, panels, and applets are
its subclasses.
A window not contained inside
another window. Used to hold
other GUI components.
An invisible container that holds
UI components. Panels can be
nested.
A base class for creating a Java
applet.
A popup window or message box
used as a temporary window to
receive additional31info or provide
notification that an event has

GUI Helper Classes


Dimension
Font

Classes in the java.awt


package

LayoutManager
1

Heavyweight

FontMetrics
Object

Color

Panel

Applet

JApplet

Window

Frame

JFrame

Dialog

JDialog

Graphics
Component

Container

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.

JComponent

Swing Components
in the javax.swing package

JPanel

Lightweight

32

Some GUI Helper Classes


Container Class
java.awt.Color

Description
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()

Creates a default frame with no title.

+JFrame(title: String)

Creates a frame with the specified title.

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

Specifies the size of the frame.

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

Specifies the upper-left corner location of the frame.

+setVisible(visible: boolean): void

Sets true to display the frame.

+setDefaultCloseOperation(mode: int): void

Specifies the operation when the frame is closed.

+setLocationRelativeTo(c: Component):
void

Sets the location of the frame relative to the specified component.


If the component is null, the frame is centered on the screen.

+pack(): void

Automatically sets the frame size to hold the components in the


frame.

JFrame is a top-level container to hold GUI


components

38

A. Open your Chapter1 NetBeans project


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

39

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 frames window.
3. Specify what to do if a user closes the window.
4. Display the frame.

41

JFrame Class
javax.swing.JFrame
+JFrame()

Creates a default frame with no title.

+JFrame(title: String)

Creates a frame with the specified title.

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

Specifies the size of the frame.

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

Specifies the upper-left corner location of the frame.

+setVisible(visible: boolean): void

Sets true to display the frame.

+setDefaultCloseOperation(mode: int): void

Specifies the operation when the frame is closed.

+setLocationRelativeTo(c: Component):
void

Sets the location of the frame relative to the specified component.


If the component is null, the frame is centered on the screen.

+pack(): void

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
arguments
EXIT_ON_CLOSE

Exit the application when the


frame is closed.

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.
DISPOSE_ON_CLOSE

HIDE_ON_CLOSE

Close the frame and continue


running.
43

The Frames Constructor


The work involved in creating the
frames 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 components class.
E.g., to create a button, just create an
instance of JButton.

45

To your MyFrame class

Add a button object

46

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 containers 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.

You might also like