HiLCoE
School of Computer Science and
Technology
Object Oriented Programming
CHAPTER - 5
GUI
Introduction GUI
So far, our programs have communicated with the user only through
text: the program displays text on the screen, and the user types text
back.
While this works, it feels limited compared to the applications we
use every day.
Think about your favorite apps on your phone or computer they
don’t ask you to type every command in words. Instead, you click
buttons, drag items, choose from menus, and see results
instantly in windows. This is the world of GUIs Stands for
Graphical User Interfaces (GUIs).
Introduction GUI
With Java, we can go beyond simple text and create interactive
applications that look and feel like real software. Using Java GUI
libraries, Java GUI Toolkits or Java GUI Frameworks (AWT or
Abstract Window Toolkit, Swing and JavaFX), we can design programs
that:
Display windows instead of just the console.
Use buttons, checkboxes, and text fields to get input.
Provide menus, sliders, and dialog boxes for interaction.
Add images, colors, and layouts to make software more user-friendly and
professional.
In other words, a GUI lets us build programs that are not only functional
but also fun to use.
GUI
In Java, we can build graphical applications using special libraries (also
called GUI frameworks) AWT, Swing, and JavaFX.
These toolkits give us ready-made components like buttons, windows, and
text fields, so we don’t have to build everything from scratch.
A component is simply an object with which the user can interact.
Think of the things you usually see in any software window:
Labels : display information (like a name tag on a door).
Text Fields: where the user types input (like writing on a notepad inside the house).
Buttons: clicked to perform actions (like pressing a doorbell to make something
happen).
Checkboxes: used to turn options on or off (like flipping a light switch).
allows us to interact with our programs through mouse movements, button
clicks, key presses, and so on.
GUI
To build a GUI in Java, there are three basic ingredients we need to
understand:
GUI Component Sets : these are the building blocks of the interface.
Examples include buttons, labels, text fields, check boxes, and more.
They form the visible parts of our program that users interact with.
Think of them like the “furniture” in a room each one has a specific purpose.
Component Arrangement (Layout) : just like arranging furniture in a
house, GUI components must be organized properly on the screen.
This arrangement is controlled by Layout Managers, which decide
where buttons, text fields, and other components should appear. A well-
arranged layout makes the program look clean and easy to use.
GUI
Response to User Requests (Events) : a GUI is not just about displaying
components; it must also respond to user actions.
For example:
Clicking a button may save data.
Typing in a text field may update the display.
Checking a box may enable or disable a feature.
These actions are called events, and we write code to handle them.
Using AWT Components
When we move from text-based programs to GUIs in Java, one of the
first tools we encounter is the Abstract Window Toolkit (AWT).
AWT is an API (Application Programming Interface) that allows us
to create windows-based applications with elements such as buttons,
text fields, checkboxes, radio buttons, and scrollbars.
An API is a set of tools, classes, methods, and rules that allows
programmers to interact with a system or library without needing
to know its internal details.
A key feature of AWT is that its tools are implemented using each
platform’s native GUI toolkit.
Using AWT Components
This also means AWT is platform-dependent. A GUI built on one system
may look slightly different on another. For example, the same button might
appear rectangular in Windows and rounded in macOS. This can reduce
consistency.
On Windows, AWT buttons look like real Windows buttons. On macOS, they
look like macOS buttons. On Linux, they follow the Linux look and feel. This
makes applications look natural on every system.
The AWT components are 'heavyweight', rely on local platform's
windowing system for look and feel. Components are tied to native system
calls.
they are rendered in their own (opaque) windows and thus are expensive to
use, they must be rectangular and cannot have transparent backgrounds, and
they are not willing to being subclassed
Using AWT Components
Why AWT is important?
AWT was the foundation of GUI programming in Java.
It introduced the concepts of components, containers, layouts, and
events, which are still used in modern GUI frameworks.
Later, Swing was developed as an improved GUI toolkit built on top of
AWT. Swing provides a richer set of GUI controls and is more
lightweight and flexible than AWT.
Nowadays, most GUI programs in Java use Swing or JavaFX, but
learning AWT helps us understand the roots of GUI programming in
Java.
Using AWT Components
• Java AWT components are platform-dependent i.e. components are
displayed according to the view of operating system.
• The [Link] package provides classes for AWT API such as
TextField, Label, TextArea, RadioButton, CheckBox, Choice, List
etc.
• AWT is the foundation upon which Swing is made i.e Swing is a
improved GUI API that extends the AWT.
• But now a days AWT is merely used because most GUI Java
programs are implemented using Swing because of its rich
implementation of GUI controls and light-weighted nature.
Java AWT Hierarchy
Java AWT Hierarchy
Java AWT Hierarchy
In AWT, every visible element is called a Component. But components
cannot exist on their own they need to be placed inside a Container.
Component any element like a like the button, text fields, scroll bars,
etc. are called components. In Java AWT, there are classes for each
component as shown in above diagram. In order to place every
component in a particular position on a screen, we need to add them to a
container.
Container a special component that can hold other components. For
example, if you want to place a button, lables and a text field together,
you put them inside a container.
The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
op-level container that represents a graphical window. It has no border or title by default and requires an associated Fra
Java AWT Hierarchy
There are four types of containers in Java AWT:
1. Window : a top-level container with no border or title bar. It serves as a
base for other containers like Frame and Dialog.
2. Panel :
A simple container with no title bar, border, or menu.
Used to group components like buttons and text fields. An instance of Panel
class creates a container, in which we can add components.
3. Frame : The Frame is the container that contain title bar and border
and can have menu bars. It can have other components like button, text
field, scrollbar etc.
Frame is most widely used container while developing an AWT application.
op-level container that represents a graphical window. It has no border or title by default and requires an associated Fra
Java AWT Hierarchy
4. Dialog :
A small popup window with a border and title.
Used for messages, confirmations, or inputs.
Unlike frames, dialogs cannot be maximized or minimized.
How to use AWT Components
To use AWT components in Java, import the [Link] package and instantiate
classes like Frame, Button, Label, TextField, and TextArea to build a
graphical user interface (GUI). Create windows using Frame and add
components to Panel or Frame containers
Core Steps to Use AWT Components
Import necessary classes: Start by importing the required AWT classes from [Link]
package.
Create a Frame: Instantiate a Frame object, which serves as the main window for your
application.
Add Components: Create instances of various AWT components, such as Button, Label,
TextField, or TextArea.
Add Components to a Container: Add to the Frame or a Panel using methods like add().
Set Frame Properties: Make the Frame visible by setting its size, title, and setting
setVisible(true).
Example of AWT
import [Link].*;
import [Link].*;
public class MyWindow extends Frame {
public MyWindow() {
// Create a button
Button btn = new Button("Click Me");
[Link](50, 100, 80, 30);
add(btn);
setSize(300, 200);
setLayout(null);
setVisible(true);
// Close window event
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
What is Swing?
After learning about AWT, the next step in Java GUI development is
Swing.
Swing is a more advanced GUI toolkit that was introduced to overcome
the limitations of AWT. Unlike AWT, which is platform-dependent,
Swing components are written entirely in Java. This makes them
platform-independent and ensures that the GUI looks the same on every
operating system and lightweight components.
Java Swing toolkit is a part of Java Foundation Classes (JFC) that is used
to create window-based applications.
Java Foundation Classes (JFC) is a set of Java libraries for building
graphical user interfaces (GUIs) and rich graphics in Java
applications, encompassing Swing components.
What is Swing?
Swing is a graphical user interface (GUI) toolkit for Java, forming part of
the Java Foundation Classes (JFC). It provides a comprehensive set of
components for building desktop applications with rich graphical
functionality and interactivity.
Why Swing is better than AWT?
Lightweight – Components are not tied to native system calls.
Rich set of controls – Provides more advanced widgets such as tables, trees,
tabbed panes, sliders, progress bars, and tooltips.
Pluggable Look-and-Feel (LAF) – You can change how your GUI looks
(Windows-style, Metal, Nimbus, etc.) without changing your code.
Event handling is more powerful – Easier to connect actions with
components.
Extensible – You can customize or even create new components easily.
Hierarchy of Java Swing classes
Swing classes
All Swing components are part of the [Link] package.
Swing Containers
Like AWT, Swing also has containers to hold components:
JFrame – The main window with title bar and border (just like Frame
in AWT).
JDialog – A popup dialog window for messages or input.
JPanel – A simple container for grouping components.
JApplet – Used to create applets (now outdated, but part of Swing).
Swing classes
Swing Components: All Swing components are part of the [Link]
package.
Some commonly used Swing components include:
JButton – A push button.
JLabel – Displays text or images.
JTextField – Single-line input field.
JTextArea – Multi-line input field.
JCheckBox – A checkbox for multiple selections.
JRadioButton – A radio button for exclusive selections.
JComboBox – A drop-down menu.
JTable – A table for displaying data.
Swing classes
Swing Components: All Swing components are part of the [Link]
package.
In summary:
Swing took the foundation of AWT and improved it by making
components platform-independent, lightweight, and much richer.
It’s one of the most widely used GUI libraries in Java and is still
taught as the standard before moving to JavaFX.
JavaFX, which is the modern toolkit for rich desktop applications.
A Visual Guide to Swing Components
JButton
JCheckBox
JComboBox JList
JTextField
JSpinner
JSlider
JPasswordField
JMenu JLabel
JRadioButton
A Visual Guide to Swing Components
• Top-Level Containers
JApplet
JDialog JFrame
• General-Purpose Containers
JPanel
JScrollPane
JTabbedPane
Commonly used Methods of Component class
Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int height) sets size of the component.
sets the layout manager for the
public void setLayout(LayoutManager m)
component.
sets the visibility of the component. It is
public void setVisible(boolean b)
by default false.
Returns the current position of the
getLocation()
component.
Shows (true) or hides (false) the
setVisible(boolean b)
component.
setBackground(Color c) Sets the background color.
What is JavaFX?
After AWT (the beginning) and Swing (the improvement), Java
introduced JavaFX as the modern GUI toolkit.
JavaFX was designed to replace Swing for building rich, modern, and
interactive desktop applications. Unlike Swing, which mainly focuses
on traditional GUIs, JavaFX supports advanced UI features, making
applications look sleek, responsive, and closer to mobile or web apps.
Think of it this way:
AWT = Old-style basic phone 📞
Swing = Feature phone with more controls 📱
JavaFX = Modern smartphone with touch, animations, and
multimedia support
What is JavaFX?
After AWT (the beginning) and Swing (the improvement), Java
introduced JavaFX as the modern GUI toolkit.
Why JavaFX? (Advantages over Swing)
Modern UI Controls Buttons, tables, sliders, media players, charts, and even
web views are available.
CSS Styling You can design GUIs like websites, using CSS to style buttons,
colors, fonts, and layouts.
FXML Support A special XML-based language to design UIs separately
from logic (like HTML for layout).
Rich Graphics and Media Supports 2D/3D graphics, audio, video, and
animation.
Responsive Design Works smoothly across devices with scalable layouts.
Better Performance Built on modern graphics pipelines for faster rendering.
What is JavaFX?
JavaFX Architecture
Stage – The main window (like JFrame in Swing).
Scene – Holds all UI elements inside the stage (like a canvas).
Nodes – Every UI element (button, text, image, shape) is a node.
Example hierarchy:
Stage → Scene → Nodes (Button, Label, TextField, etc.)
Why Learn JavaFX Today?
JavaFX is now the preferred way to build Java desktop apps because:
It supports modern designs (with CSS).
It allows separation of design and code (with FXML).
It can even run on embedded devices and be integrated with web technologies.
In fact, many developers use JavaFX to build apps that feel almost like mobile apps or
modern desktop software.
JavaFX Components
JavaFX Components
Some commonly used JavaFX components include:
Button – A clickable button.
Label – Displays text.
TextField – Single-line input.
TextArea – Multi-line input.
CheckBox & RadioButton – For choices.
ComboBox – Drop-down list.
TableView – For displaying data.
ImageView – For displaying images.
WebView – Embeds a mini web browser!
Charts – Pie charts, line charts, bar charts, etc.
Simple Java Swing Example
import [Link].*; // Import all Swing classes (JFrame, JButton, JOptionPane, etc.)
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame window (empty window) is created.
JButton b=new JButton("click");//creating instance of JButton the label "click" is created.
[Link](130,100,100, 40);//x axis, y axis, width, height (w=100, h=40)
[Link](b);//adding button in JFrame
[Link](400,500);//400 width and 500 height // frame size is set to 400 X 500
[Link](null);//using no layout managers,so the button on the exact position u specified.
[Link](true);//making the frame visible . The frame is made visible.
} }
Example of Swing by Association inside constructor
import [Link].*;
public class Simple {
JFrame f; // Declare a JFrame reference variable named 'f'
Simple(){ // Constructor: runs when you create new Simple()
f=new JFrame();//creatinstanceofJFrame// Create a new window (top-level Swing container)
JButton b=new JButton("click");//creating instance of JButton //a button with the text "click”
[Link](130,100,100, 40); //Set button (horizontal) x=130, vertical y=100, wi=100, hei=40
[Link](b);//adding button in JFrame // Add the button to the Jframe's content pane
[Link](400,500);//Set the frame size to 400 (width) x 500 (height) pixels
[Link](null);//Disable layout managers (use absolute positions via setBounds)
[Link](true);// Make the frame visible on screen
}
public static void main(String[] args) { // Entry point of the program
new Simple(); // Create an instance of Simple (calls the constructor above)
} }
Class Exercise Question Swing
• Write a Java Swing program that creates a simple GUI
window with the following requirements:
• The window should have the title "My Simple GUI
Window".
• Set the window size to 400 pixels wide and 300 pixels high.
• Make sure the program closes completely when the window
is closed.
• Display the window on the screen.
Class Exercise Question Swing
import [Link].*;
public class MySimpleGUI {
public static void main(String[] args) {
// Create a new JFrame (the main window)
JFrame frame = new JFrame("My Simple GUI Window");
// Set the window size to 400x300 pixels
[Link](400, 300);
// Make sure the program exits when the window is closed
[Link](JFrame.EXIT_ON_CLOSE);
// Display the window on the screen
[Link](true);
}
}
Simple example of Swing by inheritance
import [Link].*;
public class Simple2 extends JFrame{ // Define class 'Simple2' which inherits from JFrame
// This means Simple2 itself is a JFrame window
JFrame f; // Declare a JFrame variable
Simple2(){ // Constructor: runs when we create a new Simple2 object
JButton b=new JButton("click"); // Create a button with label "click"
[Link](130,100,100, 40); // Set button position (x=130, y=100)
// and size (width=100, height=40)
add(b); // Add the button directly to the JFrame (since we extend JFrame)
setSize(400,500); // Set the window size: 400 width, 500 height
setLayout(null); // Disable layout manager use absolute positioning
setVisible(true); // Make the window visible on screen
}
public static void main(String[] args) {
new Simple2(); // Create a new instance of Simple2 (calls constructor)
}}
Class Exercise Question Swing
• Exercise 1: Simple Label and Button
• Write a Java Swing program that inherits from the JFrame
class and performs the following tasks:
1. Create a window titled "Label and Button Example".
2. Set the window size to 400 × 300 pixels.
3. Add a label with the text "Welcome to Swing!".
4. Add a button labeled "Change Text".
5. When the button is clicked, update the label text to "Button
Clicked!".
Class Exercise Question Swing
• Exercise 2: Simple Form
• Write a Java Swing program that inherits from the JFrame
class and performs the following tasks:
1. Create a window titled “Multiple Buttons Example ".
2. Set the window size to 400 × 300 pixels.
3. Add three buttons labeled: "Red", "Green", and "Blue".
4. When the user clicks on each button, change the background
color of the window to match the button’s label.
Clicking "Red" → background turns red
Clicking "Green" → background turns green
Clicking "Blue" → background turns blue
Points To Remember
• Import the [Link] and [Link] package to use the classes and
methods of Swing.
• While creating a frame (either by instantiating or extending Frame
class), following two attributes are must for visibility of the frame:
– setSize(int width, int height);
– setVisible(true);
• When you create objects of other components like Buttons,
TextFields, etc. Then you need to add it to the frame by using the
method - add(Component's Object);
• You can add the following method also for resizing the frame -
setResizable(true);
Java Swing Components and Containers
• A container holds a group of components. It provides a space where a
component can be managed and displayed. Containers are of two
types:
• Top level Containers
– It inherits Component and Container of AWT.
– It cannot be contained within other containers.
– Example: JFrame, JDialog, JApplet
• Lightweight Containers
– It inherits JComponent class.
– It is a general purpose container.
– It can be used to organize related components together.
– Example: JPanel
Swing JButton
• The JButton class is used to create a labeled button that has platform
independent implementation. The application result in some action when
the button is pushed. It inherits AbstractButton class.
import [Link].*; // Import Swing classes (JFrame, JButton, etc.)
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example"); // Creates a top-level window (frame)
with the title "Button Example"
JButton b=new JButton("Click Here"); // Creates a button with label "Click Here"
[Link](50,100,95,30); // Sets the button's position and size
[Link](b); // Adds the button to the frame
[Link](400,400); // Sets the frame size: width=400, height=400
[Link](null); // Disables layout managers
[Link](true); // Makes the frame visible on the screen
} }
Java JLabel
• The object of JLabel class is a component for placing text in a container.
It is used to display a single line of read only text. The text can be
changed by an application but a user cannot edit it directly. It inherits
JComponent class.
Constructor Description
Creates a JLabel instance with no image
JLabel()
and with an empty string for the title.
Creates a JLabel instance with the
JLabel(String s)
specified text.
Creates a JLabel instance with the
JLabel(Icon i)
specified image.
Creates a JLabel instance with the
JLabel(String s, Icon i, int
specified text, image, and horizontal
horizontalAlignment)
alignment.
Example
import [Link].*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example"); // Creates a frame with the title "Label
Example
JLabel l1,l2; // Declares two JLabel variables
l1=new JLabel("First Label."); // Creates the first label with the text "First Label.
[Link](50,50, 100,30); // Sets its position and size
l2=new JLabel("Second Label.");
[Link](50,100, 100,30); // Creates the second label with the text "Second Label.
[Link](l1); [Link](l2); // Adds both labels to the frame
[Link](300,300); // Sets the frame size to 300px width and 300px height
[Link](null);
[Link](true);
} }
Java JTextField
• The object of a JTextField class is a text component that allows the
editing of a single line text. It inherits JTextComponent class.
JFrame f= new JFrame("TextField Example");
JTextField t1,t2; // Declares two JTextField variables (text boxes)
t1=new JTextField("Welcome."); // Creates a text field with the
default text "Welcome.
[Link](50,100, 200,30); // Sets its position and size
t2=new JTextField(“Text Field");
[Link](50,150, 200,30);
[Link](t1); [Link](t2); // Add both text fields to the frame
[Link](400,400); // Sets the frame size
[Link](null); // Disables layout manager
[Link](true); // Makes the frame visible on the screen
Java JTextArea
• The object of a JTextArea class is a multi line region that displays
text. It allows the editing of multiple line text. It inherits
JTextComponent class
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to java");
[Link](10,30, 200,200);
[Link](area);
[Link](300,300);
[Link](null);
[Link](true);
Java JPasswordField
• The object of a JPasswordField class is a text component specialized for
password entry. It allows the editing of a single line of text. It inherits
JTextField class.
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
[Link](20,100, 80,30);
[Link](100,100,100,30);
[Link](value); [Link](l1);
[Link](300,300);
[Link](null);
[Link](true);
Java JCheckBox
• The JCheckBox class is used to create a checkbox. It is used to turn an
option on (true) or off (false). Clicking on a CheckBox changes its
state from "on" to "off" or from "off" to "on ".
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
[Link](100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
[Link](100,150, 50,50);
[Link](checkBox1);
[Link](checkBox2);
[Link](400,400);
[Link](null);
[Link](true);
Java JRadioButton
• The JRadioButton class is used to create a radio button. It is used to
choose one option from multiple options. It is widely used in exam
systems or quiz.
Jframe f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
[Link](75,50,100,30);
[Link](75,100,100,30);
ButtonGroup bg=new ButtonGroup();
[Link](r1);[Link](r2);
[Link](r1);[Link](r2);
[Link](300,300);
[Link](null);
[Link](true);
Java JComboBox
• The object of Choice class is used to show popup menu of choices.
Choice selected by user is shown on the top of a menu It inherits
Jcomponent class.
Jframe f=new JFrame("ComboBox Example"); // Creates a top-level frame with the
title "ComboBox Example
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);//Creates a JComboBox (drop-down)
[Link](50, 50,90,20); //size of combo box: x=50, y=50, width=90, height=20
[Link](cb); // Adds the combo box component to the frame
[Link](null); // Disables layout manager
[Link](400,500); // Sets the frame size: width=400, height=500
[Link](true) //Makes the frame visible on the screen
Java JList
• The object of JList class represents a list of text items. The list of text
items can be set up so that the user can choose either one item or multiple
items. It inherits JComponent class.
JFrame f= new JFrame(); // Create a top-level window (a frame)
DefaultListModel<String> l1 = new DefaultListModel<>(); // Model to
hold the list's data (Strings)
[Link]("Item1"); // Add items into the model
[Link]("Item2");
[Link]("Item3");
[Link]("Item4");
JList<String> list = new JList<>(l1);
[Link](100,100, 75,75);
[Link](list); // Add the list to the frame's content pane
[Link](400,400); // Set the frame size
[Link](null); // Disable layout manager
[Link](true);
Java JOptionPane
• The JOptionPane class is used to provide standard dialog boxes
such as message dialog box, confirm dialog box and input dialog
box. These dialog boxes are used to display information or get
input from the user. The JOptionPane class inherits JComponent
class.
• Java JOptionPane Example: showMessageDialog()
Jframe f=new JFrame();
[Link](f,"Hello, Welcome to Java.");
• Java JOptionPane Example: showInputDialog()
JFame f=new JFrame();
String name=[Link](f,"Enter Name");
Java JTable
• The JTable class is used to display data in tabular form. It is composed
of rows and columns.
Jframe f=new JFrame(); // Create a new JFrame
String data[][]={// Create a 2D array (rows and columns) to hold table data
{"101","Amit","670000"}, {"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"}; // Create a 1D array
JTable jt=new JTable(data,column); // Create a Jtable using
[Link](30,40,200,300); // position (x=30, y=40) & size (w=200, h=300)
JScrollPane sp=new JScrollPane(jt); // Add the JTable into a JScrollPane
[Link](sp); // Add the scroll pane (which contains the table) to the JFrame
[Link](300,400);
[Link](true);
Java JMenuBar, JMenu and JMenuItem
• The JMenuBar class is used to display menubar on the
window or frame. It may have several menus.
• The object of JMenu class is a pull down menu component
which is displayed from the menu bar. It inherits the
JMenuItem class.
• The object of JMenuItem class adds a simple labeled menu
item. The items used in a menu must belong to the JMenuItem
or any of its subclass.
Example
JMenu menu, submenu; // Declare menu and submenu objects
JMenuItem i1, i2, i3, i4, i5; // Declare menu item objects
JFrame f= new JFrame("Menu and MenuItem Example"); // Create a JFrame window with the title
JMenuBar mb=new JMenuBar(); // Create a menu bar (the horizontal bar at the top of the window)
menu=new JMenu("Menu"); // Create the main menu named "Menu"
submenu=new JMenu("Sub Menu"); // Create a submenu named "Sub Menu"
i1=new JMenuItem("Item 1"); // Create menu items with text labels Item 1 to 5
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
[Link](i1); [Link](i2); [Link](i3); // Add menu items (i1, i2, i3 directly to the main menu
[Link](i4); [Link](i5); // Add menu items (i4, i5) to the submenu
[Link](submenu); // Add the submenu itself to the main menu
[Link](menu); // Add the main menu to the menu bar
[Link](mb); // Attach the menu bar to the JFrame
[Link](400,400); // Set the size of JFrame (w=400, h=400)
[Link](null);
[Link](true);
Java JPanel
• The JPanel is a simplest container class. It provides space in which an
application can attach any other component. It inherits the JComponents
class.
JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel(); // Create a new JPanel (container hold buttons, labels, etc.)
[Link](40,80,200,200); // Set position (x=40, y=80) & size (w=200, h=200) of panel
[Link]([Link]); // Set the background color of the panel to gray
JButton b1=new JButton("Button 1"); // Create the first button with label "Button 1
[Link](50,100,80,30); // Set position (x=50, y=100) & size (w=80, h=30) of button 1
[Link]([Link]); // Set the background color of button 1 to yellow
JButton b2=new JButton("Button 2"); // Create the second button with label "Button 2
[Link](100,100,80,30);
[Link]([Link]);
[Link](b1); [Link](b2); // Add both buttons to the panel
[Link](panel); // Add the panel (its buttons) into the JFrame
[Link](400,400);
[Link](null); [Link](true);
Exercise
• Write a program that creates the following image
Layout Managers
• Associated with containers
• provide a level of abstraction to automatically map your user interface
on all windowing systems
• Automate the layout of elements
– When elements are added to the container
– When the window is resized
• automatically adjust the positions and sizes of the elements.
• Layout managers control:
– Where components appear
– What sizes they are
– How they react when they are resized
Layout Managers
• The LayoutManagers are used to arrange components in a particular
manner.
• setLayout(...) This is a container like JFrame, JPanel
• It is used to tell the container which layout manager to use.
• [Link](new LayoutManagerType(...));
• [Link](new FlowLayout()); // use FlowLayout
• [Link](new GridLayout(3,3)); // use GridLayout
• There are the following classes that represent the layout managers:
• This is a specific layout manager class in Swing
– FlowLayout: places components in a row, wrapping to the next line if needed.
– GridLayout : arranges components in equal-sized rows and columns.
– BorderLayout: divides the container into five regions: North, South, East, West, and
Center
– GridBagLayout : the most flexible; allows components of different sizes and
positions in a grid-like structure.
Hierarchy of Layout Managers
Java BorderLayout
• The BorderLayout is used to arrange the components in five regions:
north, south, east, west, and center. Each region (area) may contain one
component only. It is the default layout of a frame or window.
• The BorderLayout provides five constants for each region:
– public static final int NORTH
– public static final int SOUTH
– public static final int EAST
– public static final int WEST
– public static final int CENTER
• Constructors of BorderLayout class:
– BorderLayout(): creates a border layout but with no gaps between
the components.
– BorderLayout(int hgap, int vgap): creates a border layout with the
given horizontal and vertical gaps between the components.
Example
Jframe f = new JFrame();
// creating buttons with labels
JButton b1 = new JButton("NORTH"); // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH"); // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST"); // the button will be labeled as EAST
JButton b4 = new JButton("WEST"); // the button will be labeled as WEST
JButton b5 = new JButton("CENTER"); // the button will be labeled as CENTER
// Optional set layout with gaps (20px horizontal, 15px vertical)
//[Link](new BorderLayout(20, 15));
// Adding buttons to BorderLayout regions
[Link](b1, [Link]); // b1 will be placed in the North Direction
[Link](b2, [Link]); // b2 will be placed in the South Direction
[Link](b3, [Link]); // b2 will be placed in the East Direction
[Link](b4, [Link]); // b2 will be placed in the West Direction
[Link](b5, [Link]); // b2 will be placed in the Center
[Link](300, 300);
[Link](true);
Java GridLayout
• The Java GridLayout class is used to arrange the components in a
rectangular grid. One component is displayed in each rectangle.
• Constructors of GridLayout class
– GridLayout(): creates a grid layout with one column per component
in a row.
– GridLayout(int rows, int columns): creates a grid layout with the
given rows and columns but no gaps between the components.
– GridLayout(int rows, int columns, int hgap, int vgap): creates a
grid layout with the given rows and columns along with given
horizontal and vertical gaps.
Example
Jframe frameObj = new JFrame(); // Create a new JFrame object
JButton btn1 = new JButton("1"); // Create 9 JButton objects with labels "1" to "9"
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9"); // Add the buttons to the frame
[Link](btn1); [Link](btn2); [Link](btn3);
[Link](btn4); [Link](btn5); [Link](btn6);
[Link](btn7); [Link](btn8); [Link](btn9);
// setting the grid layout using the parameterless constructor
/ setting grid layout of 3 rows and 3 columns
// [Link](new GridLayout(3,3));
//[Link](new GridLayout(3, 3, 20, 25)); //Horz gap =20, vert Gap=25
[Link](new GridLayout());
[Link](300, 300);
[Link](true);
Example
FlowLayout
• The Java FlowLayout class is used to arrange the components in a line, one after
another (in a flow). It is the default layout of the applet or panel.
– Fields of FlowLayout class
– public static final int LEFT
– public static final int RIGHT
– public static final int CENTER
– public static final int LEADING
– public static final int TRAILING
• Constructors of FlowLayout class
– FlowLayout(): creates a flow layout with centered alignment and a default 5
unit horizontal and vertical gap.
– FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.
– FlowLayout(int align, int hgap, int vgap): creates a flow layout with the
given alignment and the given horizontal and vertical gap.
Example
Jframe frameObj = new JFrame(); // Create a new JFrame
JButton b1 = new JButton("1"); // Create 10 buttons
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("10");
// adding the buttons to frame
[Link](b1); [Link](b2); [Link](b3); [Link](b4);
[Link](b5); [Link](b6); [Link](b7); [Link](b8);
[Link](b9); [Link](b10);
[Link](new FlowLayout()); // By default, it arranges components in a row, centered
//[Link](new FlowLayout([Link]));// // setting flow layout of right alignment
//[Link](new FlowLayout([Link], 20, 25)); // Hor= 20 , Ver =25
[Link](300, 300);
[Link](true);
Class Exercise
Write a java code which creates the following GUI
Write a java code to show
GridBagLayoutDemo application.
The Java Event Handling
• Event-Driven Programming
• An event: a type of signal to the program that something has
happened
• The event is generated by external user actions such as
– mouse movements, mouse button clicks, etc.
• The GUI component on which an event is generated is called
the source object
• Programmer writes code to respond to the various events
that may occur
The Java Event Handling
• The Event Model
– Defines a standard and consistent mechanism to generate and process events
– Events are supported by the [Link]. Package
– Basically, an Event Model is based on the following three components:
• event sources
• event objects
• event listeners
• Event Sources
– Event sources are objects that generates an event: menus, buttons, text fields
etc.
– Events are generated when the objects internal states are changed in some
way
– Event sources have methods to add event listeners to them
• For example: addActionListener()
– Event source reports on events and notifies all its listeners
The Java Event Handling
• Event Objects
– Objects that represent a user action (e.g. mouse click, or moving mouse)
– contain reference to source that generates the event and other event
information.
– When an event happens an event source sends an event object to its
event listeners
– Event can be generated as a consequence of:
• Person Interaction with the elements of GUI
– Pressing a button, Entering a character, Selecting an item in a
list, Click a mouse
• System generated events
– Timer, System Failure
– EventObject is the superclass
• ActionEvent, MouseEvent, etc. are the subclasses that we use
The Java Event Handling
• Event Listeners
– are objects that respond when an event occurs
– If the event listener has been added to an event source, the
listener will be called when an event occurs on that source.
– Any event listener is specific to an event source.
• For example, you'd have one kind of event listener to respond to
the click of a button on your mouse, and another to respond to
the press of a key on your keyboard.
– Listeners are interfaces, not classes
• Class MyButtonListener implements ActionListener
{…}
The Java Event Handling
EventObject
User
action
Generate Notify listener
an event
Trigger an event
Source Object Listener Object
Register a listener object Event Handler
Important Event Classes and Interface in Java
Event Classes Description Listener Interface
When a button is
clicked or a list item is
ActionEvent double-clicked, an ActionListener
ActionEvent is
triggered.
This event indicates a
MouseEvent mouse action occurred MouseListener
in a component
The Key event is
triggered when the
KeyEvent KeyListener
character is entered
using the keyboard.
Important Event Classes and Interface in Java
An event that indicates
ItemEvent whether an item was ItemListener
selected or not.
when the value of a
TextEvent textarea or text field is TextListener
changed
generated when the
MouseWheelEvent MouseWheelListener
mouse wheel is rotated
Registering the Source With Listener
• To perform Event Handling, we need to register the source with the
listener.
• Syntax:
addTypeListener()
• where Type represents the type of event.
Example: For ActionEvent we use addActionListener() to register.
Different interfaces consists of different methods
Listener Interface Methods
ActionListener •actionPerformed()
• mousePressed()
• mouseClicked()
• mouseEntered()
MouseListener
• mouseExited()
• mouseReleased()
MouseWheelListener •mouseWheelMoved()
TextListener •textChanged()
•keyTyped()
KeyListener •keyPressed()
•keyReleased()
ItemListener •itemStateChanged()
Java Event Handling Code
• Within class: The main class implements the listener interface and
handles events itself.
• Other Class: A separate class is created to handle events.
• Anonymous Class: The listener is written directly without
creating a named class.
Within class
import [Link].*;
import [Link].*;
class MyClass extends Frame implements ActionListener{
TextField tf;
Within class: The class MyClass itself
MyClass(){
implements the listener interface.
tf=new TextField();
The main class itself implements ActionListener
[Link](60,50,170,20);
Button b=new Button("click me"); if the Listener class is the class that contains the
[Link](100,120,80,30); source object, then the reference to the Listener
//register listener object will be ‘this’
[Link](this);// current class handles the event by passing current instance
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
[Link](“Welcome");
}
public static void main(String args[]){
new MyClass();
}}
Other class
import [Link].*;
import [Link].*;
class MyClass extends Frame{
TextField tf;
MyClass(){ Other Class: A separate class Outer in the
tf=new TextField(); next slide is created to handle events.
[Link](60,50,170,20);
Button b=new Button("click me");
[Link](100,120,80,30);
//register listener
Outer o=new Outer(this);
[Link](o);//passing outer class instance from next slide class Outer
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new MyClass();}}
Cont..
import [Link].*;
class Outer implements ActionListener{
MyClass obj;
Outer(MyClass obj){
[Link]=obj;
}
public void actionPerformed(ActionEvent e){
[Link]("Hello, outher here.");
}
}
Anonymous Class
import [Link].*;
import [Link].*;
class MyClass extends Frame{
TextField tf;
MyClass(){
tf=new TextField(); Anonymous Class: The event handler is
[Link](60,50,170,20); written inline, without giving the class a
Button b=new Button("click me"); name.
[Link](50,120,80,30);
[Link](new ActionListener(){ // you attach the event handler directly at the point of use with
@Override // (new ActionListener()the listener is written directly where the button is used.
public void actionPerformed(ActionEvent e) {
[Link]("Anonymous class");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new MyClass();}}
Cont..
• Example:
– If the listener class is different class, we have to do
ListenerClass lc = new ListenerClass();
JButton btnTest = new JButton(“Test”);
[Link](lc);
– if the Listener class is the class that contains the source object,
then the reference to the Listener object will be ‘this’
[Link](this);
• The Listener must implement the appropriate Listener
interface and define methods to receive and process
notifications
Cont..
• Example
– to Listen and process the ActionEvent generated by the source
button, the Listener class must implement ActionListener
interface
– The method to be implemented is actionPerformed.
class ListenerClass implements ActionListener{
public void ActionPerformed (ActionEvent ae){
[Link](); //returns source object reference
[Link](); //returns caption of the
//source(String)
}
}
ActionEvent
• ActionEvent
– In a Button click, TextField focus on the TextField and pressing Enter
– Source that create ActionEvent
JButton, JTextField, JMenuItem
– Listener interface that the Listener class must implement is
ActionListener
– Method that the Listener should implement is
public void actionPerformed(ActionEvent ae);
– Methods
• String getActionCommand(); - returns String(text) which is the
caption on the source
• Object getSource(); - returns object reference of the source
DocumentEvent
• DocumentEvent
– occur when the content of a document changes in any way.
– Source that create ActionEvent
• JTextField, JTextArea
– Listener interface that the Listener class must implement is
DocumentListener
– Methods that the Listener should implement are:
• void changedUpdate(DocumentEvent de) : Called when the
style of some of the text in the listened-to document changes.
• void insertUpdate(DocumentEvent de): Called when text is
inserted into the listened-to document.
• void removeUpdate(DocumentEvent de): Called when text is
removed from the listened-to document.
DocumentEvent
– To get the document that generated the event, you can use
DocumentEvent’s getDocument method.
– [Link]().addDocumentListener(this);
– Note that DocumentEvent does not inherit from EventObject
like the other event classes. Thus it does not inherit the
getSource() method.
– Must import [Link] package
ItemEvent
• ItemEvent
– Source that create ItemEvent
• JCheckBox, JRadioButton, JComboBox.
– JCheckBox and JRadioButton have two state SELECTED and
DESELECTED
getStateChange() = = [Link]
– Listener interface that the Listener class must implement is
ItemListener
– Method that the Listener class should implement is
public void itemStateChange(ItemEvent ie);
– Methods
• (event object).getSource(); //returns the source object
• (event object).getStateChange() = = [Link] or
[Link]
MouseEvent:
• MouseEvent: There are two types of Listener interfaces
– MouseListener: There are five methods to be implemented
public void mouseClicked(MouseEvent me);
public void mouseEntered(MouseEvent me);
public void mouseExited(MouseEvent me);
public void mouseReleased(MouseEvent me);
public void mousePressed(MouseEvent me);
– MouseMotionListener:
public void mouseMoved(MouseEvent me);
public void mouseDragged(MouseEvent me);
WindowEvent:
• WindowEvent
– WindowListener : There are 7 methods to be implemented
windowClosing(WindowEvent)
windowOpened(WindowEvent)
windowIconified(WindowEvent)
windowDeiconified(WindowEvent)
windowClosed(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)
import [Link].*;
import [Link].*;
import [Link].*;
class BackColor extends JFrame implements ActionListener{
JButton btnCyan;
JButton btnBlack;
JButton btnCancel;
BackColor(String str){
btnCyan = new JButton(“Cyan”);
btnBlack = new JButton(“Black”);
btnCancel = new JButton(“Exit”);
Container cp = getContentPane();
setSize(200, 300);
[Link](new FlowLayout());
[Link](btnCyan);
[Link](btnBlack);
[Link](btnCancel);
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae){
if([Link]() == btnCyan)
getContentPane().setBackground([Link]);
else if([Link]() == btnBlack)
getContentPane().setBackground([Link]);
else{
dispose();
[Link](0);
}
}
public static void main(String args[]){
BackColor b = new BackColor(“My Frame”);
[Link](true);
}
}
import [Link].*;
import [Link].*;
import [Link].*;
class Calculator extends JFrame{
JButton btn[]=new JButton[16];
JTextField txtResult;
Calculator(){
String caption[]={"7", "8", "9", "/", "4", "5", "6", "*","1",
"2", "3", "-", "0", "=",".","+"};
for(int i=0;i<16;i++)
btn[i]=new JButton(caption[i]);
txtResult=new JTextField();
MyListener ml=new MyListener();
for(int i=0;i<16;i++)
btn[i].addActionListener(ml);
Container cp=getContentPane();
[Link](new BorderLayout());
[Link](txtResult,[Link]);
JPanel jp=new JPanel();
[Link](jp,[Link]);
[Link](new GridLayout(4,4));
for(int i=0;i<16;i++)
[Link](btn[i]);
pack();
}
public static void main(String args[]){
Calculator cl=new Calculator();
[Link](true);
}
}
class MyListener implements ActionListener{
public void actionPerformed(ActionEvent ae){
[Link]([Link]());
}
}
}