You are on page 1of 61

Graphical User

Interface(GUI)
using swing
Chapter Three Part I
Introduction to GUI
• GUI, which stands for Graphical User Interface, is a user-friendly visual
experience builder for Java applications.
• It comprises graphical units like buttons, labels, windows, etc. via
which users can connect with an application.
• Swing and JavaFX are two commonly used applications to create GUIs
in Java
Swing and Awt
• It is a part of Java Foundation Classes (JFC) that is used to create
window-based applications.
• It is built on the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java.
• Unlike AWT, Java Swing provides platform-independent and
lightweight components.
• The javax.swing package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
Swing Features

• Light Weight − Swing components are independent of native


Operating System's API as Swing API controls are rendered mostly
using pure JAVA code instead of underlying operating system calls.
• Rich Controls − Swing provides a rich set of advanced controls like
Tree, TabbedPane, slider, colorpicker, and table controls.
• Highly Customizable − Swing controls can be customized in a very
easy way as visual apperance is independent of internal
representation.
• Pluggable look-and-feel − SWING based GUI Application look and feel
can be changed at run-time, based on available values.
AWT vs Swing
No. Java AWT Java Swing
1) AWT components are platform-dependent. Java swing components are platform-independent.

2) AWT components are heavyweight. Swing components are lightweight.


3) AWT doesn't support pluggable look and Swing supports pluggable look and feel.
feel.
4) AWT provides less components than Swing provides more powerful components such as
Swing. tables, lists, scrollpanes, colorchooser, tabbedpane etc.

5) AWT doesn't follows MVC(Model View Swing follows MVC.


Controller) where model represents data,
view represents presentation and controller
acts as an interface between model and
view.
Hierarchy of Swing Classes
Cont’d…
• Every user interface considers the following three main aspects −
• UI Elements − These are the core visual elements the user eventually
sees and interacts with.
• Layouts − They define how UI elements should be organized on the
screen and provide a final look and feel to the GUI (Graphical User
Interface).
• Behavior − These are the events which occur when the user interacts
with UI elements.
Class & Description

S.No. Class & Description


A Component is the abstract base class for the non menu user-interface
1 controls of SWING. Component represents an object with graphical
representation

A Container is a component that can contain other SWING components


2 such as Frame,Panel,Applet ect

A JComponent is a base class for all SWING UI components. In order to


use a SWING component that inherits from JComponent, the component
3 must be in a containment hierarchy whose root is a top-level SWING
container
Container & Description

Sr.No. Container & Description


JPanel is the simplest container. It provides space in
1 which any other component can be placed, including
other panels.
2 A JFrame is a top-level window with a title and a border.
A JWindow object is a top-level window with no
3 borders and no menubar.
Methods Used in Swing

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.

public void setLayout(LayoutManager m) sets the layout manager for the component.

public void setVisible(boolean b) sets the visibility of the component. It is by


default false.
Java Swing Examples

• There are two ways to create a frame:


• By creating the object of Frame class (association)
• By extending Frame class (inheritance)
• We can write the code of swing inside the main(), constructor or any
other method.
• import javax.swing.*;
• public class FirstSwingExample {

• public static void main(String[] args) {


• JFrame f=new JFrame();//creating instance of JFrame
• JButton b=new JButton("click");//creating instance of JButton
• b.setBounds(130,100,100, 40);//x axis, y axis, width, height
• f.add(b);//adding button in JFrame

• f.setSize(400,500);//400 width and 500 height
• f.setLayout(null);//using no layout managers
• f.setVisible(true);//making the frame visible
• }
• }
Example of Swing by Association inside constructor

• import javax.swing.*;
• public class Simple {
• JFrame f;
• Simple(){
• f=new JFrame();//creating instance of JFrame

• JButton b=new JButton("click");//creating instance of JButton
• b.setBounds(130,100,100, 40);
Cont’d…
• f.add(b);//adding button in JFrame

• f.setSize(400,500);//400 width and 500 height
• f.setLayout(null);//using no layout managers
• f.setVisible(true);//making the frame visible
• }
• public static void main(String[] args) {
• new Simple();
• }
Simple example of Swing by inheritance
• import javax.swing.*;
• public class Simple2 extends JFrame{//inheriting JFrame
• JFrame f;
• Simple2(){
• JButton b=new JButton("click");//create button
• b.setBounds(130,100,100, 40);
• add(b);//adding button on frame
• setSize(400,500);
• setLayout(null);
• setVisible(true);
• }
• public static void main(String[] args) {
• new Simple2();
• }}
Java 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.
• public class JButton extends AbstractButton implements Accessible
• Example
• JButton b=new JButton(new ImageIcon("D:\\icon.png"));
• Jbutton c=new Jbutton(“click”);
Methods in JButton
Methods Description
void setText(String s) It is used to set specified text on button

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.


Cont’d…
• import javax.swing.*;
• public class ButtonExample {
• public static void main(String[] args) {
• JFrame f=new JFrame("Button Example");
• JButton b=new JButton("Click Here");
• b.setBounds(50,100,95,30);
• f.add(b);
• f.setSize(400,400);
• f.setLayout(null);
• f.setVisible(true);
• }
• }
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.
• Syntax
• public class JLabel extends JComponent implements SwingConstants,
Accessible
• import javax.swing.*;
• class LabelExample
• {
• public static void main(String args[])
• {
• JFrame f= new JFrame("Label Example");
• JLabel l1,l2;
• l1=new JLabel("First Label.");
• l1.setBounds(50,50, 100,30);
• l2=new JLabel("Second Label.");
• l2.setBounds(50,100, 100,30);
• f.add(l1); f.add(l2);
• f.setSize(300,300);
• f.setLayout(null);
• f.setVisible(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 ".
• It inherits JToggleButton class.
• Syntax
• public class JCheckBox extends JToggleButton implements Accessible
Commonly used Methods

Methods Description

AccessibleContext getAccessibleContext() It is used to get the AccessibleContext


associated with this JCheckBox.

protected String paramString() It returns a string representation of this


JCheckBox.
• import javax.swing.*;
• public class CheckBoxExample
• {
• CheckBoxExample(){
• JFrame f= new JFrame("CheckBox Example");
• JCheckBox checkBox1 = new JCheckBox("C++");
• checkBox1.setBounds(100,100, 50,50);
• JCheckBox checkBox2 = new JCheckBox("Java", true);
• checkBox2.setBounds(100,150, 50,50);
• f.add(checkBox1);
• f.add(checkBox2);
• f.setSize(400,400);
• f.setLayout(null);
• f.setVisible(true);
• }
• public static void main(String args[])
• {
• new CheckBoxExample();
• }}
Cont’d…
Java JComboBox
• he 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.
Methods in ComboBox
Methods Description
void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object anObject) It is used to delete an item to the item list.

void removeAllItems() It is used to remove all the items from the list.

void setEditable(boolean b) It is used to determine whether the JComboBox


is editable.
void addActionListener(ActionListener a) It is used to add the ActionListener.

void addItemListener(ItemListener i) It is used to add the ItemListener.


• import javax.swing.*;
• public class ComboBoxExample {
• JFrame f;
• ComboBoxExample(){
• f=new JFrame("ComboBox Example");
• String country[]={"India","Aus","U.S.A","England","Newzealand"};
• JComboBox cb=new JComboBox(country);
• cb.setBounds(50, 50,90,20);
• f.add(cb);
• f.setLayout(null);
• f.setSize(400,500);
• f.setVisible(true);
• }
• public static void main(String[] args) {
• new ComboBoxExample();
• }
• }
Cont’d…
Java JScrollBar
• The object of JScrollbar class is used to add horizontal and vertical
scrollbar. It is an implementation of a scrollbar.
• It inherits JComponent class.
• import javax.swing.*;
• class ScrollBarExample
• {
• ScrollBarExample(){
• JFrame f= new JFrame("Scrollbar Example");
• JScrollBar s=new JScrollBar();
• s.setBounds(100,100, 50,100);
• f.add(s);
• f.setSize(400,400);
• f.setLayout(null);
• f.setVisible(true);
• }
• public static void main(String args[])
• {
• new ScrollBarExample();
• }}
Cont’d…
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.
MenuExample
• import javax.swing.*;
• class MenuExample
• {
• JMenu menu, submenu;
• JMenuItem i1, i2, i3, i4, i5;
• MenuExample(){
• JFrame f= new JFrame("Menu and MenuItem Example");
• JMenuBar mb=new JMenuBar();
• menu=new JMenu("Menu");
• submenu=new JMenu("Sub Menu");
• i1=new JMenuItem("Item 1");
• i2=new JMenuItem("Item 2");
Cont’d…
• i3=new JMenuItem("Item 3");
• i4=new JMenuItem("Item 4");
• i5=new JMenuItem("Item 5");
• menu.add(i1); menu.add(i2); menu.add(i3);
• submenu.add(i4); submenu.add(i5);
• menu.add(submenu);
• mb.add(menu);
• f.setJMenuBar(mb);
• f.setSize(400,400);
• f.setLayout(null);
• f.setVisible(true);
• }
• public static void main(String args[])
• {
• new MenuExample();
• }}
Cont’d…
Java JPopupMenu
• PopupMenu can be dynamically popped up at specific position within
a component.
• It inherits the JComponent class.
• Syntax:
• public class JPopupMenu extends JComponent implements Accessibl
e, MenuElement
Cont’d…
• import javax.swing.*;
• import java.awt.event.*;
• class PopupMenuExample
• {
• PopupMenuExample(){
• final JFrame f= new JFrame("PopupMenu Example");
• final JPopupMenu popupmenu = new JPopupMenu("Edit");
• JMenuItem cut = new JMenuItem("Cut");
• JMenuItem copy = new JMenuItem("Copy");
• JMenuItem paste = new JMenuItem("Paste");
• popupmenu.add(cut); popupmenu.add(copy); popupmenu.add(paste);
• f.addMouseListener(new MouseAdapter() {

Cont’d…
• public void mouseClicked(MouseEvent e) {
• popupmenu.show(f , e.getX(), e.getY());
• }
• });
• f.add(popupmenu);
• f.setSize(300,300);
• f.setLayout(null);
• f.setVisible(true);
• }
• public static void main(String args[])
• {
• new PopupMenuExample();
• }}
Cont’d…
Java LayoutManagers
• The LayoutManagers are used to arrange components in a particular
manner.
• The Java LayoutManagers facilitates us to control the positioning and
size of the components in GUI forms.
• LayoutManager is an interface that is implemented by all the classes
of layout managers.
• There are the following classes that represent the layout managers:
Java Layout Managers
• java.awt.BorderLayout
• java.awt.FlowLayout
• java.awt.GridLayout
• java.awt.CardLayout
• java.awt.GridBagLayout
• javax.swing.BoxLayout
• javax.swing.GroupLayout
• javax.swing.ScrollPaneLayout
• javax.swing.SpringLayout etc.
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:
• 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.
Cont’d…
• import java.awt.*;
• import javax.swing.*;
• public class Border
• {
• JFrame f;
• Border()
• {
• f = new JFrame();
• // creating buttons
• JButton b1 = new JButton(“Add");; // the button will be labeled as NORTH
• JButton b2 = new JButton(“Sub");; // the button will be labeled as SOUTH
• JButton b3 = new JButton(“Mult");; // the button will be labeled as EAST
• JButton b4 = new JButton(“div");; // the button will be labeled as WEST
• JButton b5 = new JButton(“moduls");; // the button will be labeled as CENTER
Cont’d…
• f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
• f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
• f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
• f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
• f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center

• f.setSize(300, 300);
• f.setVisible(true);
• }
• public static void main(String[] args) {
• new Border();
• }
• }
GridLayout class
• 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
• import java.awt.*;
• import javax.swing.*;
• public class MyGridLayout{
• JFrame f;
• MyGridLayout(){
• f=new JFrame();
• JButton b1=new JButton("1");
• 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");
Cont’d…
• JButton b7=new JButton("7");
• JButton b8=new JButton("8");
• JButton b9=new JButton("9");
• // adding buttons to the frame
• f.add(b1); f.add(b2); f.add(b3);
• f.add(b4); f.add(b5); f.add(b6);
• f.add(b7); f.add(b8); f.add(b9);
• // setting grid layout of 3 rows and 3 columns
• f.setLayout(new GridLayout(3,3));
• f.setSize(300,300);
• f.setVisible(true);
• }
• public static void main(String[] args) {
• new MyGridLayout();
• } }
Cont’d…
Java 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.
• 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.
SWING - Event Handling
• Change in the state of an object is known as Event, i.e., event
describes the change in the state of the source.
• Events are generated as a result of user interaction with the graphical
user interface components.
• For example, clicking on a button, moving the mouse, entering a
character through keyboard, selecting an item from the list, and
scrolling the page are the activities that causes an event to occur.
Types of Event
• The events can be broadly classified into two categories −
• Foreground Events − These events require direct interaction of the user.
• They are generated as consequences of a person interacting with the
graphical components in the Graphical User Interface.
• For example, clicking on a button, moving the mouse, entering a character
through keyboard, selecting an item from list, scrolling the page, etc.
• Background Events − These events require the interaction of the end user.
Operating system interrupts, hardware or software failure, timer expiration,
and operation completion are some examples of background events.
What is Event Handling?
• Event Handling is the mechanism that controls the event and decides
what should happen if an event occurs.
• This mechanism has a code which is known as an event handler, that
is executed when an event occurs.
• Java uses the Delegation Event Model to handle the events.
• This model defines the standard mechanism to generate and handle
the events.
Cont’d…
• The Delegation Event Model has the following key participants.
• Source − The source is an object on which the event occurs. Source is
responsible for providing information of the occurred event to it's
handler. Java provide us with classes for the source object.
• Listener − It is also known as event handler. The listener is responsible
for generating a response to an event.
• The listener waits till it receives an event.
• Once the event is received, the listener processes the event and then
returns.
SWING - Event Classes

Sr.No. Method & Description


Object getSource()
1
The object on which the Event initially occurred.
String toString()
2
Returns a String representation of this EventObject.
Event Classes
Sr.No. Class & Description

AWTEvent
1 It is the root event class for all SWING events. This class and its subclasses
supercede the original java.awt.Event class.

ActionEvent
2 The ActionEvent is generated when the button is clicked or the item of a list is
double-clicked.
InputEvent
3 The InputEvent class is the root event class for all component-level input events.

KeyEventO
4 n entering the character the Key event is generated.

MouseEvent
5 This event indicates a mouse action occurred in a component.
Cont’d…
WindowEvent
6 The object of this class represents the change in the state of a window.

AdjustmentEvent
7 The object of this class represents the adjustment event emitted by
Adjustable objects.

ComponentEvent
8 The object of this class represents the change in the state of a window.

ContainerEvent
9 The object of this class represents the change in the state of a window.

MouseMotionEvent
10 The object of this class represents the change in the state of a window.
• public class Addition extends Frame implements ActionListener {
• public TextField txt1,txt2;//used to create TextField(swing)
• public Button add;
• public Label lb1,lb2,result;
• public Addition(){//constructor used to initialize
• setLayout(new FlowLayout());
• lb1 = new Label("enter Number One");
• this.add(lb1);
• txt1=new TextField(10);
• this.add(txt1);
• lb2 = new Label("enter Number Two");
• this.add(lb2);
• txt2=new TextField(10);
• this.add(txt2);
• add= new Button("Add");
• this.add(add);
• result = new Label("Result:");
• this.add(result);
• add.addActionListener(this);
• }
• public void actionPerformed(ActionEvent e) {
• if(e.getSource()==add){
• double number1=Double.parseDouble(txt1.getText());
• double number2=Double.parseDouble(txt2.getText());
• double sum=number1+number2;
• result.setText("Sum of two Number is"+sum);

• }
• }
• public static void main(String[] args) {
• Addition ad = new Addition();
• ad.setSize(100,200);
• ad.setTitle("Addition of Two Numbers");
• ad.setVisible(true);

• }
Drag and Drop Techniques
Assignment
• Create Simple Calculator Using Drag and Drop
• Create Notepad using Java swing code
The End of Part 1

Thankyou For Your Attention!!!

You might also like