0% found this document useful (0 votes)
41 views66 pages

Week 10 - GUI Part I

Uploaded by

tinashii-
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views66 pages

Week 10 - GUI Part I

Uploaded by

tinashii-
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 66

STIA1123 : Programming 2

GUI (Part 1)
Objectives
– To define a subclass of JFrame to implement a customized frame
window.
– To be able to arrange GUI component objects on a window using
basic layout managers and nested panels
– To write GUI application programs using JButton, JLabel,
JTextField and other common GUI objects from the javax.swing
package
– To write GUI application programs using Netbeans Swing GUI Tool
Graphical User Interface

• In Java, GUI-based programs are implemented by


using classes from the javax.swing and java.awt
packages.

• The Swing classes provide greater compatibility


across different operating systems. They are fully
implemented in Java, and behave the same on
different operating systems.
The differences between Swing and AWT

Swing:
•Swing is part of the java foundation classes.
•Swing components are platform-independent.
•Swing components are lightweight components because swing sits on
the top of AWT.
•Swing components is uses the screen resource of an ancestor
instead of having their own and that's why called lightweight or
lighter component.

AWT:
•AWT is called the abstract window tool.
•AWT components are platform-dependent.
•AWT components are heavyweight components
•AWT component are associated with native screen resource and
called heavyweight component.
Various Java GUI Components
from the javax.swing package

Label Text Check Radio


field Box Button

Button

Combo Box
Sample GUI Objects
• Various GUI components
from the javax.swing
package.
AWT Class Hierarchy (java.awt package)
Swing Class Hierarchy (javax.swing)
GUI Classes
■ Can be classified into three groups

■ Container classes
■ Ex: JFrame, JPanel, JApplet
■ To contain other components

■ Component classes
■ JButton, JTextField, etc are subclasses of JComponent

■ Helper classes
■ Graphics, Color, Font, etc
■ Used by components and containers to draw and place objects
Container Classes

Container classes can


contain other GUI
components.
Container Classes

■ A container contains and arranges other components


(including other container) through the use of layout
managers, which use specific layout policies to
determine where components should go as a function
of the size of the container. JPanel and JFrame are
example of container for Java.
■ Used to contain other GUI components
■ Window, Panel, Frame, Dialog and Applet are the container
classes for AWT components
■ To work with Swing components, use Component,
Container, JFrame, JPanel,JDialog and JApplet
■ Container
■ Used to group components.
■ A layout manager is used to position and place components in
container
Container Classes

■ JFrame
■ Is a window not contained inside another window. It is the container
that holds other swing UI components
■ JPanel
■ An invisible container that holds UI components
■ Panel can be nested
■ Can place panels inside a container that includes a panel
■ JDialog
■ A pop-up windows or message box to receive additional information
from the user or provide notification that an event has occurred
■ JApplet – a subclass of Applet. Must extend JApplet to create a
Swing-based applet
Swing GUI Components

■ Component is a superclass of all the UI classes


■ JComponent is a superclass of all the lightweight Swing
components
■ JComponent is an abstract class, cannot use new
JComponent to create an instance of JComponent
■ Use the constructor of subclasses of JComponent to create
JComponent instances.
■ An instance of a subclass can invoke the accessible
method defined in its superclass
Swing GUI Components – class hierarchy
GUI Helper Classes

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

• Frame is a window that is not contained inside


another window.
• Frame is the basis to contain other user interface
components in Java GUI applications.
• The Frame class can be used to create windows. The
Frame class contains rudimentary functionalities to
support features found in any frame window.
• For Swing GUI programs, use JFrame class to create
windows.
Two Ways to Create a Window Using
JFrame

• First approach
– Declare & Create object of type JFrame
– Use various methods to manipulate window
• Second approach
– Create class containing application program by extending
definition of class JFrame
– Utilizes mechanism of inheritance
Creating Frames

1) First approach:
import javax.swing.*;
public class MyFrame
{
public static void main(String[] args)
{
JFrame frame = new JFrame(“MyFrame");
frame.setSize(400, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
}
}
Creating Frames

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

setVisible() and setSize() –


400 methods in Component class

setDefaultCloseOperation
(EXIT_ON_CLOSE)
- terminate when the frame is
closed
300
Creating Frames
2) Second approach :

import javax.swing.*;
public class MyFrame extends JFrame
{
public MyFrame()
{
setTitle(“MyFrame");
setSize(400, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public static void main(String[] args)


{
MyFrame myFrame = new MyFrame();
}
}
The Content Pane of a Frame

• The content pane is where we put GUI objects


such as buttons, labels, scroll bars, and others.
• We access the content pane by calling the frame’s
getContentPane method.

This gray area is the


content pane of this
frame.
Changing the Background Color

• Here's how we can change the background color


of a content pane to blue:
Container contentPane = getContentPane();
contentPane.setBackground(Color.BLUE);
Placing GUI Objects on a Frame

• There are two ways to put GUI objects on the


content pane of a frame:
– Use a layout manager
• FlowLayout
• BorderLayout
• GridLayout
• others
– Use absolute positioning
• null layout manager
Placing a Button
• A JButton object a GUI component that represents
a pushbutton.
• Here's an example of how we place a button with
FlowLayout.

contentPane.setLayout(
new FlowLayout());
JButton okButton
= new JButton("OK");
JButton cancelButton
= new JButton("CANCEL");
contentPane.add(okButton);
contentPane.add(cancelButton);
Layout Managers

• The layout manager determines how the GUI


components are added to the container (such as
the content pane of a frame)
• Layout managers are set in containers using the
setLayout(LayoutManager) method in a container
• Examples of basic layout manager:
– FlowLayout
– BorderLayout
– GridLayout
FlowLayout

• In using this layout, GUI components are placed in


left-to-right order.
– When the component does not fit on the same line, left-
to-right placement continues on the next line.
• As a default, components on each line are
centered.
• When the frame containing the component is
resized, the placement of components is adjusted
accordingly.
FlowLayout Sample

This shows
the placement
of five buttons
by using
FlowLayout.
FlowLayout

•The components are arranged in


the container from left to right in
the order in which they were
added.

•When one row becomes filled, a


new row is started.

•FlowLayout can be aligned in 3


ways:

FlowLayout.LEFT – left aligned


FlowLayout.RIGHT – right aligned
FlowLayout.CENTER – center aligned
FlowLayout Constructors

• public FlowLayout(int align, int hGap, int vGap)


Constructs a new FlowLayout with a specified alignment, horizontal gap,
and vertical gap. The gaps are the distances in
pixel between components.

• public FlowLayout(int alignment)


Constructs a new FlowLayout with a specified alignment and a default gap
of five pixels for both horizontal and vertical.

• public FlowLayout()
Constructs a new FlowLayout with a default center alignment and a default
gap of five pixels for both horizontal and vertical.
import java.awt.*;
import javax.swing.*;
//import java.awt.event.*;

public class TestFlowLayout extends JFrame


{
public TestFlowLayout()
{
super(“Using flowLayout");
Container cpane = getContentPane();
cpane.setLayout(new FlowLayout(FlowLayout.LEFT,20,10));
for (int i=1; i<7;i++)
cpane.add(new JButton("button "+i)); 20
setSize(300,200);
setVisible(true);
}
public static void main(String[] arg)
{ 10
TestFlowLayout teks = new TestFlowLayout();
teks.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}
BorderLayout

• This layout manager divides the container into five


regions: center, north, south, east, and west.
• The north and south regions expand or shrink in
width only
• The east and west regions expand or shrink in
height only
• The center region expands or shrinks on both
height and width.
• Not all regions have to be occupied.
BorderLayout Sample

e.g To add button 1 in the north region & button 2 in the south region :
cPane.add(new JButton("button 1"), BorderLayout.NORTH);
cPane.add(new JButton("button 2"), BorderLayout.SOUTH);
GridLayout

• This layout manager placesGUI components on


equal-size N by M grids.
• Components are placed in top-to-bottom, left-to-
right order.
• The number of rows and columns remains the
same after the frame is resized, but the width and
height of each region will change.
GridLayout Sample
Using Panels as Containers

• Panels act as smaller containers for grouping user interface


components.
• It is recommended that you place the user interface components in
panels and place the panels in a frame. You can also place panels
in a panel.
• To add a component to JFrame, you actually add it to the content
pane of JFrame. To add a component to a panel, you add it directly
to the panel using the add method.
Create a JPanel

example :
Container cpane = getContentPane();
JPanel pan = new JPanel(); // create a panel
pan.add(new JButton(“Click”)); // add a button in the
panel
cpane.add(pan) // add the panel in the container
label TextField Top
panel

Middle
Text Area panel

button button Bottom


panel

There are 3 panels :


top panel – has 2 components that are label, textfield
- 2 components are arranged with flowLayout

middle panel – has a component: text area. It is arranged with Gridlayout

bottom panel – has 2 components that are buttons


- 2components are arranged with Flowlayout

All panels are arrranged with borderlayout


top panel –north middle panel –center bottom panel –South
import java.awt.*;
import javax.swing.*;

public class GUIwithPanels extends JFrame {

public GUIwithPanels() {
super("Using Panels in JFrame");
Container ctr = getContentPane();
ctr.setLayout(new BorderLayout());

JPanel panelTop = new JPanel();


ctr.add(panelTop, BorderLayout.NORTH);
JLabel label = new JLabel("Name");
JTextField txtField = new JTextField(20);
panelTop.setLayout(new FlowLayout());
panelTop.add(label);
panelTop.add(txtField);

JPanel panelMid = new JPanel();


ctr.add(panelMid, BorderLayout.CENTER);
JTextArea txtArea = new JTextArea();
panelMid.setLayout(new GridLayout());
panelMid.add(txtArea);

JPanel panelBottom = new JPanel();


ctr.add(panelBottom, BorderLayout.SOUTH);
JButton btn1 = new JButton("Send");
JButton btn2 = new JButton("Cancel");
panelBottom.setLayout(new FlowLayout());
panelBottom.add(btn1);
panelBottom.add(btn2);
setSize(300, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

} // constructor

public static void main(String[] arg) {


GUIwithPanels app = new GUIwithPanels();
}

}
Step in Creating Panel

• Set a layout manager for a container (frame).


• Create a panel
• Set a layout for the panel.
• Add the panel in the container (frame)
• Create a component that to be added in the panel
• Add the component in the panel
GUI Classes for Handling Text

• The Swing GUI classes JLabel, JTextField, and


JTextArea deal with text.
• A JLabel object displays uneditable text (or image).
• A JTextField object allows the user to enter a single line of
text.
• A JTextArea object allows the user to enter multiple lines
of text. It can also be used for displaying multiple lines of
uneditable text.
JLabel

• We use a JLabel object to display a label.


• A label can be a text or an image.
• When creating an image label, we pass ImageIcon
object instead of a string.
JLabel textLabel = new JLabel("Please enter your name");
contentPane.add(textLabel);

JLabel imgLabel = new JLabel(new ImageIcon("cat.gif"));


contentPane.add(imgLabel);
JTextField

• We use a JTextField object to accept a single line


to text from a user. An action event is generated
when the user presses the ENTER key.
• The getText method of JTextField is used to
retrieve the text that the user entered.

JTextField input = new JTextField( );


contentPane.add(input);
JLabel
(with a text)
JLabel
(with an image)

JTextField
JTextArea
• We use a JTextArea object to display or allow the user to
enter multiple lines of text.
• The setText method assigns the text to a JTextArea,
replacing the current content.
• The append method appends the text to the current text.
JTextArea textArea
= new Hello
JTextArea( ); the lost
. . . world
textArea.setText("Hello\n");
textArea.append("the lost ");
textArea.append("world"); JTextArea
• TextArea containing six words.
Designing a Swing GUI in NetBeans
IDE

• In real world, you will create your GUI using tool such as the
NetBeans IDE GUI Builder
• Here we will design the GUI for an application that can calculate
the area and perimeter of a rectangle given its length & width as
the input
• The GUI is shown below:
Designing a Swing GUI in NetBeans
IDE

Free Design

•In the IDE's GUI Builder, you can build your forms by simply
putting components where you want them as if you were using
absolute positioning.

•The GUI Builder figures out which layout attributes are required
and then generates the code for you automatically

•You need not concern yourself the layout managers.


Steps for designing the GUI
1. Create a Netbeans project
• In Netbeans, choose File > New Project
•In the Categories pane, select the Java node and in the Projects pane,
choose Java Application. Click Next.
•Enter RectangleApp in the Project Name field and
specify the project location.
•Leave the Use Dedicated
Folder for Storing Libraries
checkbox unselected.
•Ensure that the Create Main
Class checkbox is selected
and clear the Create Main
Class field.
•Click Finish.
Steps for designing the GUI
2. Creating a JFrame Container
To add a JFrame container:
•In the Projects window, right-click the RectangleApp node
and choose New > JFrame Form.
•Enter RectangleAppGUI as the Class Name.
• Enter my.rectangleApp as the package.
• Click Finish.
Steps for designing the GUI
3. Getting Familiar with the GUI Builder
When we added the JFrame container, the newly-created RectangleAppGUI form
is opened in the GUI Builder's Design Area and three additional windows appeared
automatically , enabling you to navigate, organize, and edit GUI forms.
The windows are as follows:
i) Design Area. The GUI Builder's primary window for creating and editing
Java GUI forms.
ii) Navigator. Provides a representation of all the components, both visual and
non-visual, in your application as a tree hierarchy.
iii)Palette. A customizable list of available components containing tabs for JFC/Swing,
AWT, and JavaBeans components, as well as layout managers.
iv) Properties Window. Displays the properties of the component currently selected
in the GUI Builder, Navigator window, Projects window, or Files window.
Steps for designing the GUI
3. Getting Familiar with the GUI Builder

Palette

Design
Area

Properties
Navigator
Steps for designing the GUI
4. Adding Components
To add a JLabel to the form:
-In the Palette window, select (click your mouse) the Label component
from the Swing Controls category.
Steps for designing the GUI
4. Adding Components
-Move your mouse into the Design Area.
. When the guidelines appear indicating that the JLabel is
positioned in the top left corner with a small
margin at the top and left edges, click again your mouse to place the Label.

-The JLabel is added to the form and a corresponding


node representing the component is added to the Navigator window.
Steps for designing the GUI
4. Adding Components
Before going further, we need to edit the JLabel text.
To edit the display text of a JLabel:

-Double-click the JLabel to select its display text.


-Type ‘Length:’ and press Enter.

The JLabel's new name is displayed and the component's width


adjusts as a result of the edit.
Steps for designing the GUI
4. Adding Components
To add a JTextField to the form:
- In the Palette window, select the Text Field component.
- Move the cursor immediately to the right of the ‘Length:’ JLabel
-When the horizontal guideline appears indicating that the JTextField's baseline
is aligned with the JLabel and the spacing between them is suggested with a
vertical guideline, click to position the JTextField.
- The JTextField snaps into position in the form aligned with the JLabel's
baseline, as shown below:
Steps for designing the GUI
4. Adding Components
To remove the text inside the JTextField & resize it:

-Double-click the JTextField to select its display text & press Delete.
- The width of the JTextField will be reduced. You need to resize (make it
wider) the JTextField by dragging the JTextField's right edge resize handle
toward the right edge of the enclosing JFrame
Steps for designing the GUI
4. Adding Components
To add the remaining three JLabels & JTextFields
- Repeat all the previous steps to add Jlabels & JTextFields
- Ensure that all the texts for the labels & textfields have been changed
correctly (e.g. second JLabel’s text is ‘Width :’ etc.)
- Once finished, you should have your GUI as shown below:
Steps for designing the GUI
4. Adding Components
To add JButton to the form:
- In the Palette window, select the Button component from the Swing Controls
category.
- Move the JButton below of the Perimeter: JTextField

-Set the display text for the JButton.


-You can edit the button's text by right-clicking the button and choosing Edit Text.
-Enter ‘Compute’ for the button
Steps for designing the GUI
4. Adding Components
To add another JButton
- Repeat all the previous steps to add the second JButton
- The second JButton text must be set to ‘Reset’
- Once finished, you should have your GUI as shown below:
Steps for designing the GUI
5. Set the JFrame Container size & title
To resize your JFrame (main container):
- Bring your mouse to the bottom right corner of the frame
- Click & drag your mouse diagonally up or down to resize the frame
according
your preference
Steps for designing the GUI
5. Set the JFrame Container size & title
To set the JFrame title:
- Click the JFrame and ensure that it is highlighted (with orange-colored border)

- In the JFrame Properties Window, click the ‘title' property field.


Steps for designing the GUI
5. Set the JFrame Container size & title
To set the JFrame title:
- Type the desired title (e.g. ‘My Rectangle App’) in the title property field
Steps for designing the GUI
6. Running your App
To run your RectangleAppGUI program:
-Click the Source view tab to view the source codes that have been generated by
Netbeans

Generated
codes
Steps for designing the GUI
6. Running your App
To run your RectangleAppGUI program:
-Right Click your mouse in the generated codes area & select “Run File”
Steps for designing the GUI
6. Running your App
You can see your GUI when the program runs:

You might also like