You are on page 1of 34

Lecture 17

JAVA Swing

Dr. P M Shelke
• Java Swing tutorial 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.
• The Java Foundation Classes (JFC) are a set of GUI components which
simplify the development of desktop applications.
• 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.
Difference between AWT and 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 feel. Swing supports pluggable look and
feel.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane etc.

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


where model represents data, view represents
presentation and controller acts as an interface
between model and view.
Hierarchy of Java Swing classes
• Container classes are classes that can have other components on it.
So for creating a GUI, we need at least one container object. There
are 3 types of containers.
1. Panel: It is a pure container and is not a window in itself. The sole
purpose of a Panel is to organize the components on to a window.
2. Frame: It is a fully functioning window with its title and icons.
3. Dialog: It can be thought of like a pop-up window that pops out when
a message has to be displayed. It is not a fully functioning window
like the Frame.
• All components in swing are JComponent which can be added to container
classes.
• JFrame – A frame is an instance of JFrame. Frame is a window that can have title,
border, menu, buttons, text fields and several other components. A Swing
application must have a frame to have the components added to it.
JPanel – A panel is an instance of JPanel. A frame can have more than one panels
and each panel can have several components. You can also call them parts of
Frame. Panels are useful for grouping components and placing them to
appropriate locations in a frame.
• JLabel – A label is an instance of JLabel class. A label is unselectable text and
images. If you want to display a string or an image on a frame, you can do so by
using labels. In the above example we wanted to display texts “User” &
“Password” just before the text fields , we did this by creating and adding labels
to the appropriate positions.
• JTextField – Used for capturing user inputs, these are the text boxes where user
enters the data.
• JPasswordField – Similar to text fields but the entered data gets hidden and
displayed as dots on GUI.
• JButton – A button is an instance of JButton class.
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.

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.
Frame example
import javax.swing.*;
public class Simpleframe extends JFrame {
public Simpleframe()
{
this.setSize(400, 400);
this.setTitle("Simple Frame");
this.setVisible(true);
}
public static void main(String[] args) {
Simpleframe sf1=new Simpleframe();
}
}
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.

Constructor Description

JButton() It creates a button with no text and icon.


JButton(String s) It creates a button with the specified text.
JButton(Icon i) It creates a button with the specified icon object.
Commonly used Methods of AbstractButton class:

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.


import javax.swing.*;
public class Simpleframe extends JFrame {
public Simpleframe() {
this.setSize(400, 400);
this.setTitle("Simple Frame");
this.setLayout(null);

JButton b1=new JButton();


b1.setText("Click Me");
b1.setBounds(120, 120, 180, 60);
this.add(b1);
this.setVisible(true);
}
public static void main(String[] args) {
Simpleframe sf1=new Simpleframe();
}
}
import javax.swing.*;

public class Simpleframe extends JFrame {

public Simpleframe()
{
this.setSize(400, 400);
this.setTitle("Simple Frame");
this.setLayout(null);

JLabel l1=new JLabel();


l1.setText("WELCOME");
l1.setBounds(120,20, 180, 40);
this.add(l1);

JTextField tf1=new JTextField();


tf1.setBounds(120, 60, 180, 70);
this.add(tf1);

JButton b1=new JButton();


b1.setText("Click Me");
b1.setBounds(120, 140, 180, 60);
this.add(b1);

this.setVisible(true);
}

public static void main(String[] args) {

Simpleframe sf1=new Simpleframe();

}
Java Layout Manger

• The Layout manager is used to layout (or arrange) the GUI java
components inside a container.
• There are many layout managers, but the most frequently used are-
• Java BorderLayout
• Java FlowLayout
• Java GridBagLayout
BorderLayout
• A BorderLayout places components in
up to five areas: top, bottom, left,
right, and center. // Define new buttons with different regions
JButton jb1 = new JButton(“Button 1 (PAGE_START”);
• It is the default layout manager for JButton jb2 = new JButton(“Long-Named Button
4(PAGE_END)”);
every java JFrame JButton jb3 = new JButton(“Button 3(LINE_START)");
JButton jb4 = new JButton(“Button 5(LINE_END)");
JButton jb5 = new JButton(“Button 2(CENTER");

// Define the panel to hold the buttons


JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(jb1, BorderLayout.NORTH);
panel.add(jb2, BorderLayout.SOUTH);
panel.add(jb3, BorderLayout.WEST);
panel.add(jb4, BorderLayout.EAST);
panel.add(jb5, BorderLayout.CENTER);
FlowLayout
JFrame frame = new JFrame(“FlowLayoutDemo");
FlowLayout is the default layout manager for every JPanel.
// Define new buttons
JButton jb1 = new JButton("Button 1");
It simply lays out components in a single row one after JButton jb2 = new JButton("Button 2");
the other. JButton jb3 = new JButton("Button 3");
JButton jb4 = new JButton(“Long-Named Button 4");
JButton jb5 = new JButton(“5");

// Define the panel to hold the buttons


JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(jb1);
panel.add(jb2);
panel.add(jb3);
panel.add(jb4);
panel.add(jb5);

// Set the window to be visible as the default to be false


frame.add(panel);
frame.pack();
frame.setVisible(true);
GridBagLayout

• It is the more sophisticated of all layouts.


• It aligns components by placing them within a grid of cells, allowing
components to span more than one cell.
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

• 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.
Event Handling Mechanism
• 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.
• 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. From the point of view of Java implementation, the
listener is also an object. The listener waits till it receives an event. Once the
event is received, the listener processes the event and then returns.
• The benefit of this approach is that the user interface logic is
completely separated from the logic that generates the event.
• The user interface element is able to delegate the processing of an
event to a separate piece of code.
• In this model, the listener needs to be registered with the source
object so that the listener can receive the event notification.
• This is an efficient way of handling the event because the event
notifications are sent only to those listeners who want to receive
them.
Steps Involved in Event Handling

• Step 1 − The user clicks the button and the event is generated.
• Step 2 − The object of concerned event class is created automatically
and information about the source and the event get populated within
the same object.
• Step 3 − Event object is forwarded to the callback method of the
registered listener class.
• Step 4 − The method is gets executed and returns.
ActionListener interface
• The Java ActionListener is notified whenever you click on the button
or menu item.
• It is notified against ActionEvent.
• The ActionListener interface is found in java.awt.event package.
• It has only one method: actionPerformed().
• The common approach is to implement the ActionListener.
• If you implement the ActionListener class, you need to
follow 3 steps:

• 1) Implement the ActionListener interface in the class:


public class ActionListenerExample Implements ActionLis
tener

• 2) Register the component with the Listener:


component.addActionListener(instanceOfListenerclass);

• 3) Override the actionPerformed() method:


public void actionPerformed(ActionEvent e){
//Write the code here
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class Simpleframe extends JFrame implements ActionListener {

JTextField tf1;
public Simpleframe()
{
this.setSize(400, 400);
this.setTitle("Simple Frame");
this.setLayout(null);

JLabel l1=new JLabel();


l1.setText("WELCOME");
l1.setBounds(120,20, 180, 40);
this.add(l1);

tf1=new JTextField();
tf1.setBounds(120, 60, 180, 70);
this.add(tf1);

JButton b1=new JButton();


b1.setText("Click Me");
b1.setBounds(120, 140, 180, 60);
this.add(b1);
b1.addActionListener(this);
this.setVisible(true);

public static void main(String[] args) {

Simpleframe sf1=new Simpleframe();

@Override
public void actionPerformed(ActionEvent arg0) {
tf1.setText("VIIT");

} }
Event classes
• Event classes represent the event.

Sr.No. Class & Description

AWTEvent It is the root event class for all SWING events. This class and its subclasses supercede the
1 original java.awt.Event class.
ActionEvent The ActionEvent is generated when the button is clicked or the item of a list is double-clicked.
2

3 InputEvent The InputEvent class is the root event class for all component-level input events.

4 KeyEvent On entering the character the Key event is generated.

5 MouseEvent This event indicates a mouse action occurred in a component.

6 WindowEvent The object of this class represents the change in the state of a window.

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

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

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

10 MouseMotionEvent The object of this class represents the change in the state of a window.

11 PaintEvent The object of this class represents the change in the state of a window.
Event Listeners
• Event listeners represent the interfaces responsible to handle events.

Sr.No. Class & Description


1 ActionListener This interface is used for receiving the action events.
2 ComponentListener This interface is used for receiving the component events.
3 ItemListener This interface is used for receiving the item events.
4 KeyListener This interface is used for receiving the key events.
5 MouseListener This interface is used for receiving the mouse events.
6 WindowListener This interface is used for receiving the window events.
7 AdjustmentListener This interface is used for receiving the adjustment events.
8 ContainerListener This interface is used for receiving the container events.
9 MouseMotionListener This interface is used for receiving the mouse motion events.
10 FocusListener This interface is used for receiving the focus events.
• JScrollBar
• Jmenu
• JList
• JRadioButton class
• JTextArea class
• JComboBox class
• JTable class
• JColorChooser class
• JProgressBar class
• JSlider class
JScrollBar

import javax.swing.*;
class example{
example(){
JFrame a = new JFrame("example");
JScrollBar b = new JScrollBar();
b.setBounds(90,90,40,90);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[]){
new example();
}
}
JPanel
import java.awt.*;
import javax.swing.*;
public class Example{
Example(){
JFrame a = new JFrame("example");
JPanel p = new JPanel();
p.setBounds(40,70,200,200);
JButton b = new JButton("click me");
b.setBounds(60,50,80,40);
p.add(b);
a.add(p);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[])
{
new Example();
}
}
import javax.swing.*;

class Example{ JMenu


JMenu menu;
JMenuItem a1,a2;
Example()
{

JFrame a = new JFrame(“Simple Frame");

menu = new JMenu(“File");

JMenuBar m1 = new JMenuBar();

a1 = new JMenuItem(“New");

a2 = new JMenuItem(“Save");
menu.add(a1);
menu.add(a2);
m1.add(menu);
a.setJMenuBar(m1);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}

public static void main(String args[])


{

new Example();
}
}
import javax.swing.*; JList
public class Example
{
Example(){
JFrame a = new JFrame("example");
DefaultListModel<String> l = new DefaultListModel< >();
l.addElement("first item");
l.addElement("second item");
JList<String> b = new JList< >(l);
b.setBounds(100,100,75,75);
a.add(b);
a.setSize(400,400);
a.setVisible(true);
a.setLayout(null);
}
public static void main(String args[])
{
new Example();
}
}
import javax.swing.*;
JComboBox
public class Example{
JFrame a;
Example(){
a = new JFrame("example");
string courses[] = { "core java","advance java", "java servlet"};
JComboBox c = new JComboBox(courses);
c.setBounds(40,40,90,20);
a.add(c);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[])
{
new Example();
}
}

You might also like