SlideShare une entreprise Scribd logo
1  sur  51
Graphical User
Interface (GUI)
Objectives
 After you have read and studied this chapter, you should
be able to
 Define a subclass of JFrame to implement a customized frame
window.
 Write event-driven programs using Java's delegation-based event
model
 Arrange GUI objects on a window using layout managers and
nested panels
 Write GUI application programs using
JButton, JLabel, ImageIcon, JTextField, JTextArea, JCheckBox, JR
adioButton, JComboBox, JList, and JSlider objects from the
javax.swing package
 Write GUI application programs with menus
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.
Various Java GUI
Components from the
javax.swing package
Button
Label Text
field
Check
Box
Radio
Button
Combo Box
Sample GUI Objects
 Various GUI components
from the javax.swing
package.
AWT Class Hierarchy (java.awt package)
AWTEvent
Font
FontMetrics
Component
Graphics
Object Color
Canvas
Button
TextComponent
Label
List
CheckBoxGroup
CheckBox
Choice
Container Panel Applet
Frame
Dialog FileDialog
Window
TextField
TextArea
MenuComponent MenuItem
MenuBar
Menu
Scrollbar
LayoutManager
Swing Class Hierarchy (javax.swing)
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
Classes in the java.awt
package
1
LayoutManager
*
 Can be classified into three groups
 Container classes
 Ex: JFrame, JPanel, JApplet
 To contain other components
 Helper classes
 Graphics, Color, Font, etc
 Used by components and containers to draw and place objects
 Component classes
 JButton, JTextField, ETC are subclasses of JComponent
GUI Classes
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
Container classes can
contain other GUI
components.
 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
 Ex. Frames, panels and applets
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
Container Classes
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.
 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
wing GUI Components – class hierarchy
JMenuItem
JCheckBoxMenuItem
AbstractButton
JComponent
JMenu
JRadioButtonMenuItem
JToggleButton JCheckBox
JRadioButton
JComboBox
JInternalFrame
JLayeredPane
JList
JMenuBar
JOptionPane
JPopupMenu
JProgressBar
JFileChooser
JScrollBar
JScrollPaneJSeparatorJSplitPane
JSlider
JTabbedPane
JTable JTableHeader
JTextFieldJTextComponent
JTextArea
JToolBar JToolTip
JTree
JRootPane
JPanel
JPasswordField
JColorChooser
JLabel
JEditorPane
JSpinner
JButton
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);
}
}
300
400
setVisible() and setSize() –
methods in Component class
setDefaultCloseOperation
(EXIT_ON_CLOSE)
- terminate when the frame is
closed
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
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));
setSize(300,200);
setVisible(true);
}
public static void main(String[] arg)
{
TestFlowLayout teks = new TestFlowLayout();
teks.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
10
20
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
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
Text Area
button button
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
Top
panel
Middle
panel
Bottom
panel
import java.awt.*;
import javax.swing.*;
public class UjiPanel extends JFrame
{
public UjiPanel()
{
super("Membuat BorderLayout");
Container bekas = getContentPane();
bekas.setLayout(new BorderLayout());
JPanel panelAtas = new JPanel();
bekas.add(panelAtas,BorderLayout.NORTH);
JLabel label = new JLabel("Nama");
JTextField txtField = new JTextField(10);
panelAtas.setLayout(new FlowLayout());
panelAtas.add(label);
panelAtas.add(txtField);
JPanel panelTengah = new JPanel();
bekas.add(panelTengah,BorderLayout.CENTER);
JTextArea txtArea = new JTextArea();
panelTengah.setLayout(new GridLayout());
panelTengah.add(txtArea);
JPanel panelBawah = new JPanel();
bekas.add(panelBawah,BorderLayout.SOUTH);
JButton btg1 = new JButton("Hantar");
JButton btg2 = new JButton("Batal");
btg2.setMnemonic('B');
panelBawah.setLayout(new FlowLayout());
panelBawah.add(btg1);
panelBawah.add(btg2);
setSize(300,200);
setVisible(true);
} // konstruktor
public static void main(String[] arg)
{
UjiPanel teks = new UjiPanel();
teks.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
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 an image)
JLabel
(with a text)
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 JTextArea( );
. . .
textArea.setText("Hellon");
textArea.append("the lost ");
textArea.append("world");
Hello
the lost world
JTextArea
 TextArea containing six words.
Adding Scroll Bars to
JTextArea
 By default a JTextArea does not have
any scroll bars. To add scroll bars, we
place a JTextArea in a JScrollPane
object.
JTextArea textArea = new JTextArea();
. . .
JScrollPane scrollText = new JScrollPane(textArea);
. . .
contentPane.add(scrollText);
 A sample window when a JScrollPane is used.
Other Common GUI
Components
 JCheckBox
 JRadioButton
 JComboBox
 JList
Menus
 The javax.swing package contains three menu-
related classes: JMenuBar, JMenu, and
JMenuItem.
 JMenuBar is a bar where the menus are placed.
There is one menu bar per frame.
 JMenu (such as File or Edit) is a group of menu
choices. JMenuBar may include many JMenu
objects.
 JMenuItem (such as Copy, Cut, or Paste) is an
individual menu choice in a JMenu object.
 Only the JMenuItem objects generate events.
Menu Components
Edit View Help
JMenuBar Edit View HelpFile
JMenu
JMenuItem
separator
Sequence for Creating
Menus
1. Create a JMenuBar object and attach it
to a frame.
2. Create a JMenu object.
3. Create JMenuItem objects and add
them to the JMenu object.
4. Attach the JMenu object to the
JMenuBar object.

Contenu connexe

Tendances

Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For SyntaxPravinYalameli
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design PatternsAnton Keks
 
Validation Controls in asp.net
Validation Controls in asp.netValidation Controls in asp.net
Validation Controls in asp.netDeep Patel
 
Graphical User Interface in JAVA
Graphical User Interface in JAVAGraphical User Interface in JAVA
Graphical User Interface in JAVAsuraj pandey
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
Graphics programming in Java
Graphics programming in JavaGraphics programming in Java
Graphics programming in JavaTushar B Kute
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in JavaNiloy Saha
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in javaGoogle
 
Java layoutmanager
Java layoutmanagerJava layoutmanager
Java layoutmanagerArati Gadgil
 
Java package
Java packageJava package
Java packageCS_GDRCST
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Object and class relationships
Object and class relationshipsObject and class relationships
Object and class relationshipsPooja mittal
 
Type casting in java
Type casting in javaType casting in java
Type casting in javaFarooq Baloch
 

Tendances (20)

Awt controls ppt
Awt controls pptAwt controls ppt
Awt controls ppt
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Validation Controls in asp.net
Validation Controls in asp.netValidation Controls in asp.net
Validation Controls in asp.net
 
Graphical User Interface in JAVA
Graphical User Interface in JAVAGraphical User Interface in JAVA
Graphical User Interface in JAVA
 
Java History
Java HistoryJava History
Java History
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Graphics programming in Java
Graphics programming in JavaGraphics programming in Java
Graphics programming in Java
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Java layoutmanager
Java layoutmanagerJava layoutmanager
Java layoutmanager
 
Java package
Java packageJava package
Java package
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Object and class relationships
Object and class relationshipsObject and class relationships
Object and class relationships
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
Java method
Java methodJava method
Java method
 
Java program structure
Java program structureJava program structure
Java program structure
 

En vedette

Graphical User Interface (Gui)
Graphical User Interface (Gui)Graphical User Interface (Gui)
Graphical User Interface (Gui)Bilal Amjad
 
Career guidance after bca
Career guidance   after bcaCareer guidance   after bca
Career guidance after bcaJIGAR MAKHIJA
 
INTRODUCTION TO SOFTWARE ENGINEERING
INTRODUCTION TO SOFTWARE ENGINEERINGINTRODUCTION TO SOFTWARE ENGINEERING
INTRODUCTION TO SOFTWARE ENGINEERINGProf Ansari
 
Presentation on bhagat singh
Presentation on bhagat singhPresentation on bhagat singh
Presentation on bhagat singhSarfaraj_alam
 
Graphical user interface of web form
Graphical user interface of web formGraphical user interface of web form
Graphical user interface of web formmentorrbuddy
 
Graphical User Interface
Graphical User Interface Graphical User Interface
Graphical User Interface Bivek Pakuwal
 
PThreads Vs Win32 Threads
PThreads  Vs  Win32 ThreadsPThreads  Vs  Win32 Threads
PThreads Vs Win32 ThreadsRobert Sayegh
 
User interfaces presentation
User interfaces presentationUser interfaces presentation
User interfaces presentationsomipam1
 
Introduction To Software Engineering
Introduction To Software EngineeringIntroduction To Software Engineering
Introduction To Software EngineeringLeyla Bonilla
 
human computer interface
human computer interfacehuman computer interface
human computer interfaceSantosh Kumar
 

En vedette (17)

Graphical User Interface (Gui)
Graphical User Interface (Gui)Graphical User Interface (Gui)
Graphical User Interface (Gui)
 
An introduction to software engineering
An introduction to software engineeringAn introduction to software engineering
An introduction to software engineering
 
Career guidance after bca
Career guidance   after bcaCareer guidance   after bca
Career guidance after bca
 
INTRODUCTION TO SOFTWARE ENGINEERING
INTRODUCTION TO SOFTWARE ENGINEERINGINTRODUCTION TO SOFTWARE ENGINEERING
INTRODUCTION TO SOFTWARE ENGINEERING
 
Bhagat Singh
Bhagat SinghBhagat Singh
Bhagat Singh
 
Presentation on bhagat singh
Presentation on bhagat singhPresentation on bhagat singh
Presentation on bhagat singh
 
Bhagat Singh
Bhagat SinghBhagat Singh
Bhagat Singh
 
Graphical user interface of web form
Graphical user interface of web formGraphical user interface of web form
Graphical user interface of web form
 
Graphical User Interface
Graphical User Interface Graphical User Interface
Graphical User Interface
 
Matlab GUI
Matlab GUIMatlab GUI
Matlab GUI
 
User Interface
User InterfaceUser Interface
User Interface
 
Gui
GuiGui
Gui
 
Matlab GUI
Matlab GUIMatlab GUI
Matlab GUI
 
PThreads Vs Win32 Threads
PThreads  Vs  Win32 ThreadsPThreads  Vs  Win32 Threads
PThreads Vs Win32 Threads
 
User interfaces presentation
User interfaces presentationUser interfaces presentation
User interfaces presentation
 
Introduction To Software Engineering
Introduction To Software EngineeringIntroduction To Software Engineering
Introduction To Software Engineering
 
human computer interface
human computer interfacehuman computer interface
human computer interface
 

Similaire à Graphical User Interface (GUI) - 1

Similaire à Graphical User Interface (GUI) - 1 (20)

Chap1 1 1
Chap1 1 1Chap1 1 1
Chap1 1 1
 
Chap1 1.1
Chap1 1.1Chap1 1.1
Chap1 1.1
 
Swing
SwingSwing
Swing
 
Swing
SwingSwing
Swing
 
Z blue introduction to gui (39023299)
Z blue   introduction to gui (39023299)Z blue   introduction to gui (39023299)
Z blue introduction to gui (39023299)
 
Swing
SwingSwing
Swing
 
JavaAdvUnit-1.pptx
JavaAdvUnit-1.pptxJavaAdvUnit-1.pptx
JavaAdvUnit-1.pptx
 
Abstract Window Toolkit
Abstract Window ToolkitAbstract Window Toolkit
Abstract Window Toolkit
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892
 
AdvancedJava.pptx
AdvancedJava.pptxAdvancedJava.pptx
AdvancedJava.pptx
 
Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1
 
08graphics
08graphics08graphics
08graphics
 
Awt, Swing, Layout managers
Awt, Swing, Layout managersAwt, Swing, Layout managers
Awt, Swing, Layout managers
 
SWING.pptx
SWING.pptxSWING.pptx
SWING.pptx
 
Java swing
Java swingJava swing
Java swing
 
swings.pptx
swings.pptxswings.pptx
swings.pptx
 
Java AWT and Java FX
Java AWT and Java FXJava AWT and Java FX
Java AWT and Java FX
 
14a-gui.ppt
14a-gui.ppt14a-gui.ppt
14a-gui.ppt
 
Java GUI Programming for beginners-graphics.pdf
Java GUI Programming for beginners-graphics.pdfJava GUI Programming for beginners-graphics.pdf
Java GUI Programming for beginners-graphics.pdf
 
UNIT-2-AJAVA.pdf
UNIT-2-AJAVA.pdfUNIT-2-AJAVA.pdf
UNIT-2-AJAVA.pdf
 

Plus de PRN USM

Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2PRN USM
 
File Input & Output
File Input & OutputFile Input & Output
File Input & OutputPRN USM
 
Exception Handling
Exception HandlingException Handling
Exception HandlingPRN USM
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2PRN USM
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1PRN USM
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined MethodPRN USM
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - IntroPRN USM
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition StructurePRN USM
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control StructuresPRN USM
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And ExpressionPRN USM
 
Introduction To Computer and Java
Introduction To Computer and JavaIntroduction To Computer and Java
Introduction To Computer and JavaPRN USM
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...PRN USM
 
Empowering Women Towards Smokefree Homes
Empowering  Women  Towards  Smokefree  HomesEmpowering  Women  Towards  Smokefree  Homes
Empowering Women Towards Smokefree HomesPRN USM
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean ExperiencePRN USM
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...PRN USM
 
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesMalaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesPRN USM
 
Role Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlRole Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlPRN USM
 
Application Of Grants From Mhpb
Application Of Grants From MhpbApplication Of Grants From Mhpb
Application Of Grants From MhpbPRN USM
 

Plus de PRN USM (19)

Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
 
Array
ArrayArray
Array
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - Intro
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control Structures
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And Expression
 
Introduction To Computer and Java
Introduction To Computer and JavaIntroduction To Computer and Java
Introduction To Computer and Java
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
 
Empowering Women Towards Smokefree Homes
Empowering  Women  Towards  Smokefree  HomesEmpowering  Women  Towards  Smokefree  Homes
Empowering Women Towards Smokefree Homes
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean Experience
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
 
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesMalaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
 
Role Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlRole Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco Control
 
Application Of Grants From Mhpb
Application Of Grants From MhpbApplication Of Grants From Mhpb
Application Of Grants From Mhpb
 

Dernier

Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 

Dernier (20)

Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 

Graphical User Interface (GUI) - 1

  • 2. Objectives  After you have read and studied this chapter, you should be able to  Define a subclass of JFrame to implement a customized frame window.  Write event-driven programs using Java's delegation-based event model  Arrange GUI objects on a window using layout managers and nested panels  Write GUI application programs using JButton, JLabel, ImageIcon, JTextField, JTextArea, JCheckBox, JR adioButton, JComboBox, JList, and JSlider objects from the javax.swing package  Write GUI application programs with menus
  • 3. 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.
  • 4. Various Java GUI Components from the javax.swing package Button Label Text field Check Box Radio Button Combo Box
  • 5. Sample GUI Objects  Various GUI components from the javax.swing package.
  • 6. AWT Class Hierarchy (java.awt package) AWTEvent Font FontMetrics Component Graphics Object Color Canvas Button TextComponent Label List CheckBoxGroup CheckBox Choice Container Panel Applet Frame Dialog FileDialog Window TextField TextArea MenuComponent MenuItem MenuBar Menu Scrollbar LayoutManager
  • 7. Swing Class Hierarchy (javax.swing) 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 Classes in the java.awt package 1 LayoutManager *
  • 8.  Can be classified into three groups  Container classes  Ex: JFrame, JPanel, JApplet  To contain other components  Helper classes  Graphics, Color, Font, etc  Used by components and containers to draw and place objects  Component classes  JButton, JTextField, ETC are subclasses of JComponent GUI Classes
  • 9. 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 Container classes can contain other GUI components.
  • 10.  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  Ex. Frames, panels and applets Container Classes
  • 11.  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 Container Classes
  • 12. 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.
  • 13.  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
  • 14. wing GUI Components – class hierarchy JMenuItem JCheckBoxMenuItem AbstractButton JComponent JMenu JRadioButtonMenuItem JToggleButton JCheckBox JRadioButton JComboBox JInternalFrame JLayeredPane JList JMenuBar JOptionPane JPopupMenu JProgressBar JFileChooser JScrollBar JScrollPaneJSeparatorJSplitPane JSlider JTabbedPane JTable JTableHeader JTextFieldJTextComponent JTextArea JToolBar JToolTip JTree JRootPane JPanel JPasswordField JColorChooser JLabel JEditorPane JSpinner JButton
  • 15. 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.
  • 16. 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
  • 17. 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); } }
  • 18. 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); } } 300 400 setVisible() and setSize() – methods in Component class setDefaultCloseOperation (EXIT_ON_CLOSE) - terminate when the frame is closed
  • 19. 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(); } }
  • 20. 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.
  • 21. 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);
  • 22. 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
  • 23. 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);
  • 24. 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
  • 25. 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.
  • 26. FlowLayout Sample This shows the placement of five buttons by using FlowLayout.
  • 27. 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
  • 28. 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.
  • 29. 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)); setSize(300,200); setVisible(true); } public static void main(String[] arg) { TestFlowLayout teks = new TestFlowLayout(); teks.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } 10 20
  • 30. 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.
  • 32. 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.
  • 34. 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.
  • 35. 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
  • 36. label TextField Text Area button button 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 Top panel Middle panel Bottom panel
  • 37. import java.awt.*; import javax.swing.*; public class UjiPanel extends JFrame { public UjiPanel() { super("Membuat BorderLayout"); Container bekas = getContentPane(); bekas.setLayout(new BorderLayout()); JPanel panelAtas = new JPanel(); bekas.add(panelAtas,BorderLayout.NORTH); JLabel label = new JLabel("Nama"); JTextField txtField = new JTextField(10); panelAtas.setLayout(new FlowLayout()); panelAtas.add(label); panelAtas.add(txtField); JPanel panelTengah = new JPanel(); bekas.add(panelTengah,BorderLayout.CENTER); JTextArea txtArea = new JTextArea(); panelTengah.setLayout(new GridLayout()); panelTengah.add(txtArea); JPanel panelBawah = new JPanel(); bekas.add(panelBawah,BorderLayout.SOUTH); JButton btg1 = new JButton("Hantar"); JButton btg2 = new JButton("Batal"); btg2.setMnemonic('B'); panelBawah.setLayout(new FlowLayout()); panelBawah.add(btg1); panelBawah.add(btg2);
  • 38. setSize(300,200); setVisible(true); } // konstruktor public static void main(String[] arg) { UjiPanel teks = new UjiPanel(); teks.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
  • 39. 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
  • 40. 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.
  • 41. 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);
  • 42. 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);
  • 44. 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 JTextArea( ); . . . textArea.setText("Hellon"); textArea.append("the lost "); textArea.append("world"); Hello the lost world JTextArea
  • 46. Adding Scroll Bars to JTextArea  By default a JTextArea does not have any scroll bars. To add scroll bars, we place a JTextArea in a JScrollPane object. JTextArea textArea = new JTextArea(); . . . JScrollPane scrollText = new JScrollPane(textArea); . . . contentPane.add(scrollText);
  • 47.  A sample window when a JScrollPane is used.
  • 48. Other Common GUI Components  JCheckBox  JRadioButton  JComboBox  JList
  • 49. Menus  The javax.swing package contains three menu- related classes: JMenuBar, JMenu, and JMenuItem.  JMenuBar is a bar where the menus are placed. There is one menu bar per frame.  JMenu (such as File or Edit) is a group of menu choices. JMenuBar may include many JMenu objects.  JMenuItem (such as Copy, Cut, or Paste) is an individual menu choice in a JMenu object.  Only the JMenuItem objects generate events.
  • 50. Menu Components Edit View Help JMenuBar Edit View HelpFile JMenu JMenuItem separator
  • 51. Sequence for Creating Menus 1. Create a JMenuBar object and attach it to a frame. 2. Create a JMenu object. 3. Create JMenuItem objects and add them to the JMenu object. 4. Attach the JMenu object to the JMenuBar object.