0% found this document useful (0 votes)
9 views

Java Swing

Java Swing, introduced in the late 1990s, enhances GUI development in Java by providing lightweight and customizable components compared to the earlier AWT. Key components include JButton, JLabel, JTextField, and various layout managers like FlowLayout and BorderLayout, which help organize the GUI elements. Event handling in Swing allows applications to respond to user interactions, making the interface dynamic and engaging.

Uploaded by

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

Java Swing

Java Swing, introduced in the late 1990s, enhances GUI development in Java by providing lightweight and customizable components compared to the earlier AWT. Key components include JButton, JLabel, JTextField, and various layout managers like FlowLayout and BorderLayout, which help organize the GUI elements. Event handling in Swing allows applications to respond to user interactions, making the interface dynamic and engaging.

Uploaded by

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

UNIT-V

INTRODUCTION TO JAVA SWING


Java Swing was introduced as part of the Java Foundation Classes (JFC) in the late
1990s, aiming to address the limitations of the earlier Abstract Window Toolkit (AWT).
AWT is used for creating GUI in Java.AWT components are heavy weight. It means
AWT components take more system resources like memory and processor time.
Swing is used to create a graphical user interface for a Java-based application. An
interface is a dashboard that allows a user to interact with the system.
Swing provides a comprehensive set of components for building GUIs, including
buttons, text fields, panels, and more. These components are highly customizable, allowing
developers to create visually appealing and user-friendly interfaces.

SWING COMPONENTS
Swing components are the basic building blocks of an application. They are the
interactive elements in a Java application. It provides a set of lightweight components that are
not only easy to use but also customizable. Some of the important and common components of
the Java Swing class are:

 JButton
JButton class is used to create a push-button on the UI. The button can contain
some display text or image. It generates an event when clicked and double-clicked.
Example:
JButton ab = new JButton("Ok");
This constructor returns a button with text Ok on it.
JButton samp = new JButton(“PUSH”);
It returns a button with a PUSH on it.
 JLabel
JLabel class is used to render a read-only text label or images on the UI. It does
not generate any event.
Example:
JLabel name = new JLabel("This is a text label.");
This constructor returns a label with text.
JLabel ob = new JLabel(“Enter the Value”);
It returns a label with the text.

PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY 1


 JTextField
JTextField renders an editable single-line text box. A user can input non-
formatted text in the box. It does not limit the number of characters that can be input in
the box.
Example:
JTextField txtBox = new JTextField(20);
It renders a text box of 20 column width.
 JTextArea
JTextArea class renders a multi-line text box. Similar to the JTextField, a user
can input non-formatted text in the field. It does not restrict the number of characters
that the user can input in the text-area.
Example:
JTextArea txtArea = new JTextArea("This text is default text for text area.",
5, 20);
The above code renders a multi-line text-area of height 5 rows and width 20
columns, with default text initialized in the text-area.
 JPasswordField
JPasswordField is a subclass of JTextField class. It renders a text-box that
masks the user input text with bullet points. This is used for inserting passwords into
the application.
Example:
JPasswordField pwdField = new JPasswordField(15);
var pwdValue = pwdField.getPassword();
It returns a password field of 15 column width. The getPassword method gets
the value entered by the user.
 JCheckBox
JCheckBox renders a check-box with a label. The check-box has two states –
on/off. When selected, the state is on and a small tick is displayed in the box.
Example:
JCheckBox chkBox = new JCheckBox("Show Help", true);
It returns a checkbox with the label Show Help. Notice the second parameter
in the constructor. True means the check-box is defaulted to on state.
 JRadioButton

PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY 2


JRadioButton is used to render a group of radio buttons in the UI. A user can
select one choice from the group.
Example:
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton rb1 = new JRadioButton("Easy", true);
JRadioButton rb2 = new JRadioButton("Medium");
JRadioButton rb3 = new JRadioButton("Hard");
radioGroup.add(rb1);
radioGroup.add(rb2);
radioGroup.add(rb3);
The above code creates a button group and three radio button elements. All
three elements are then added to the group. This ensures that only one option out of
the available options in the group can be selected at a time. The default selected
option is set to Easy.
 JList
JList component renders a scrollable list of elements. A user can select a value or
multiple values from the list. This select behaviour is defined in the code by the
developer.
Example:
DefaultListItem cityList = new DefaultListItem();
cityList.addElement("Mumbai"):
cityList.addElement("London"):
cityList.addElement("New York"):
cityList.addElement("Sydney"):
cityList.addElement("Tokyo"):
JList cities = new JList(cityList);
cities.setSelectionModel(ListSelectionModel.SINGLE_SELECTION);
The above code renders a list of cities with 5 items in the list. The selection
restriction is set to SINGLE_SELECTION. If multiple selections are to be allowed,
set the behavior to MULTIPLE_INTERVAL_SELECTION.

PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY 3


CREATING WINDOWS AND DIALOGS

Java Swing JWindow with examples


JWindow is part of Java Swing and can appear on any part of the user's desktop. It is
different from JFrame in that JWindow does not have a title bar or window management buttons
like minimize, maximize, and close, which JFrame has. JWindow can contain several
components, such as buttons and labels.

Class Constructors

S.No. Constructor & Description

JWindow()
1
Creates a window with no specified owner.

JWindow(Frame owner)
2
Creates a window with the specified owner frame.

JWindow(GraphicsConfiguration gc)
3 Creates a window with the specified GraphicsConfiguration of a
screen device.

This class inherits methods from the following classes

 java.awt. Window
 java. awt. Container
 java. awt. Component
 java. lang. Object

PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY 4


Example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingContainerDemo
{
private JLabel headerLabel;
public void prepareGUI(){
JFrame mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
JLabel msglabel = new JLabel("Welcome to SWING Tutorial." ,
JLabel.CENTER);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
headerLabel.setText("Container in action: JWindow");
}

Java Swing JDialog with examples

PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY 5


The JDialog control represents a top-level window with a border and a title used to take
some form of input from the user. JDialog is part of the Java Swing package. Its main purpose
is to add components to the dialog, which can be customized according to user needs.
It inherits the Dialog class. Unlike JFrame, it doesn't have maximize and minimize buttons.

Constructor Description

It is used to create a modeless dialog without a


JDialog ()
title and a specified Frame owner.

It is used to create a modeless dialog with a


JDialog (Frame owner)
specified Frame as its owner and an empty title.

JDialog (Frame owner, String title, boolean It is used to create a dialog with the specified
modal) title, owner Frame, and modality.

Example :

import javax.swing.*;
import java.awt.*;
public class DialogExample {
DialogExample () {
JFrame f= new JFrame ();
JDialog d = new JDialog (f, "Dialog Example", true);
d.setLayout (new FlowLayout ());
JButton b = new JButton ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{

PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY 6


DialogExample.d. setVisible(false);
}
});
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}

EVENT HANDLING IN SWING


Event Handling in Java Swing refers to the process of capturing and responding to user-
generated events, such as button clicks, mouse movements, and keyboard inputs. It enables
developers to create applications that can dynamically react to user interactions, making the
user interface responsive and engaging.

PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY 7


It 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. Event handling involves three key components:

1. Event Sources: These are the objects that generate events, such as buttons, text fields,
and checkboxes.
2. Event Listeners: Event listeners are responsible for detecting and responding to
specific types of events. They are attached to event sources and contain the event-
handling code.
3. Event Objects: Event objects encapsulate information about the event, such as its
type and source.
The java. awt. Event package provides many event classes and Listener interfaces for
event handling.
Steps involved in event handling
 The User clicks the button and the event is generated.
 Now the object of the concerned event class is created automatically and information
about the source and the event get populated with in same object.
 Event object is forwarded to the method of registered listener class.
 The method is now executed and returns.

Example:

import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

public class EventHandlingDemo extends JFrame {

public EventHandlingDemo() {
setTitle("Event Handling Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
JButton clickButton = new JButton("Click Me");
setLayout(new FlowLayout());
add(clickButton);
JOptionPane.showMessageDialog(null, "Button Clicked!");
}

PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY 8


public static void main(String[] args) {
EventHandlingDemo example = new EventHandlingDemo();
example.setVisible(true);
}
}

In the example above, we created a simple GUI with a button. When the button is clicked, an
action event is generated, and the corresponding action listener displays a message.

LAYOUT MANAGEMENT IN SWING


In Java, graphical user interfaces (GUIs) play a vital role in creating interactive
applications. Layout managers define how components are arranged within a container, such
as a JFrame or JPanel. Java provides several layout managers to suit various design needs.
Each layout manager arranges the components attached to it according to its own policy
giving us more flexibility when designing our GUI. The most common layout managers are
 FlowLayout
 BorderLayout
 GridLayout
 CardLayout

 FlowLayout
FlowLayout is a simple layout manager that arranges components in a row, left to right.
Normally all components are set to one row, according to the order of different components.
If all components cannot be fit into one row, it will start a new row and fit the rest in.
Example:

PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY 9


JFrame frame = new JFrame("FlowLayout Example");
frame.setLayout(new FlowLayout());
frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
frame.add(new JButton("Button 3"));

 BorderLayout
BorderLayout divides the container into five regions: NORTH, SOUTH, EAST, WEST,
and CENTER. Components can be added to these regions, and they will occupy the
available space accordingly. This layout manager is suitable for creating interfaces with
distinct sections, such as a title bar, content area, and status bar.
Example:
JFrame frame = new JFrame("BorderLayout Example");
frame.setLayout(new BorderLayout());
frame.add(new JButton("North"), BorderLayout.NORTH);
frame.add(new JButton("South"), BorderLayout.SOUTH);
frame.add(new JButton("East"), BorderLayout.EAST);
frame.add(new JButton("West"), BorderLayout.WEST);
frame.add(new JButton("Center"), BorderLayout.CENTER);

1
PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY
0
 GridLayout

GridLayout arranges components in a grid with a specified number of rows and


columns. Each cell in the grid can hold a component. This layout manager is ideal for creating
a uniform grid of components, such as a calculator or a game board.
Example:
JFrame frame = new JFrame("GridLayout Example");
frame.setLayout(new GridLayout(3, 3));
for (int i = 1; i <= 9; i++)
{
frame.add(new JButton("Button " + i));
}

 CardLayout
CardLayout allows components to be stacked on top of each other, like a deck of
cards. Only one component is visible at a time, and you can switch between components using
methods like next() and previous(). This layout is useful for creating wizards or multi-step
processes.
Example:

JFrame frame = new JFrame("CardLayout Example");


CardLayout cardLayout = new CardLayout();
JPanel cardPanel = new JPanel(cardLayout);
JButton button1 = new JButton("Card 1");
JButton button2 = new JButton("Card 2");

1
PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY
1
JButton button3 = new JButton("Card 3");
cardPanel.add(button1, "Card 1");
cardPanel.add(button2, "Card 2");
cardPanel.add(button3, "Card 3");

WORKING WITH TEXT AND GRAPHICS IN SWING


The Java.awt.Graphics package includes Swing Graphics. These graphics draw
rectangles, lines, ovals, and other shapes. Custom painting is provided in Java via the
Java.awt.Graphics class. We must import this package to use it. This package also includes
graphics-managed methods and device-independent methods for drawing texts, figures, and
images. Commonly used methods of Graphics class:

1. public abstract void drawString (String str, int x, int y): is used to draw the specified
string.
2. public void drawRect (int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect (int x, int y, int width, int height): is used to fill the
rectangle with the default color and specified width and height.
4. public abstract void drawOval (int x, int y, int width, int height): is used to draw an
oval with the specified width and height.
5. public abstract void fillOval (int x, int y, int width, int height): is used to fill an oval
with the default color and specified width and height.

1
PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY
2
6. public abstract void drawLine (int x1, int y1, int x2, int y2): is used to draw a line
between the points (x1, y1) and (x2, y2).
7. public abstract void drawArc (int x, int y, int width, int height, int
startAngle, int arcAngle): is used to draw a circular or elliptical arc.
8. public abstract void fillArc(int x, int y, int width, int height, int startAngle,
int arcAngle): is used to fill a circular or elliptical arc.
9. public abstract void setColor (Color c): is used to set the graphics current
color to the specified color.
10. public abstract void setFont (Font font): is used to set the graphics current
font to the specified font.

Example:

import java.awt. *;
import javax.swing.JFrame;
public class display extends Canvas
{
public void paint (Graphics g) {
g.drawString("Hello",40,40);
setBackground(Color.WHITE);
g.fillRect(130, 30,100, 80);
g.drawOval(30,130,50, 60);
setForeground(Color.RED);
g.fillOval(130,130,50, 60);
g.drawArc(30, 200, 40,50,90,60);
g.fillArc(30, 130, 40,50,180,40);
}
public static void main(String[] args)
{
display m=new display();
JFrame f=new JFrame();
f.add(m);
f.setSize(400,400);

1
PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY
3
f.setVisible(true);
} }

USING SWING CONTROLS AND MENUS

Swing Controls
Following is the list of commonly used controls while designing GUI using SWING
 JButton
JButton class is used to create a push-button on the UI. The button can contain
some display text or image. It generates an event when clicked and double-clicked.
Example:
JButton ab = new JButton("Ok");
This constructor returns a button with text Ok on it.
JButton samp = new JButton(“PUSH”);
It returns a button with a PUSH on it.
 JLabel

1
PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY
4
JLabel class is used to render a read-only text label or images on the UI. It does
not generate any event.
Example:
JLabel name = new JLabel("This is a text label.");
This constructor returns a label with text.
JLabel ob = new JLabel(“Enter the Value”);
It returns a label with the text.

 JTextField
JTextField renders an editable single-line text box. A user can input non-
formatted text in the box. It does not limit the number of characters that can be input in
the box.
Example:
JTextField txtBox = new JTextField(20);
It renders a text box of 20 column width.
 JTextArea
JTextArea class renders a multi-line text box. Similar to the JTextField, a user
can input non-formatted text in the field. It does not restrict the number of characters
that the user can input in the text-area.
Example:
JTextArea txtArea = new JTextArea("This text is default text for text area.",
5, 20);
The above code renders a multi-line text-area of height 5 rows and width 20
columns, with default text initialized in the text-area.
 JPasswordField
JPasswordField is a subclass of JTextField class. It renders a text-box that
masks the user input text with bullet points. This is used for inserting passwords into
the application.
Example:
JPasswordField pwdField = new JPasswordField(15);
var pwdValue = pwdField.getPassword();
It returns a password field of 15 column width. The getPassword method gets
the value entered by the user.

1
PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY
5
 JCheckBox
JCheckBox renders a check-box with a label. The check-box has two states –
on/off. When selected, the state is on and a small tick is displayed in the box.
Example:
JCheckBox chkBox = new JCheckBox("Show Help", true);
It returns a checkbox with the label Show Help. Notice the second parameter
in the constructor. True means the check-box is defaulted to on state.
 JRadioButton
JRadioButton is used to render a group of radio buttons in the UI. A user can
select one choice from the group.
Example:
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton rb1 = new JRadioButton("Easy", true);
JRadioButton rb2 = new JRadioButton("Medium");
JRadioButton rb3 = new JRadioButton("Hard");
radioGroup.add(rb1);
radioGroup.add(rb2);
radioGroup.add(rb3);
The above code creates a button group and three radio button elements. All
three elements are then added to the group. This ensures that only one option out of
the available options in the group can be selected at a time. The default selected
option is set to Easy.

MENUS
The JMenuBar class is used to display menubar on the window or frame. It may have
several menus.The object of the JMenu class is a pull-down menu component which is
displayed from the menu bar. It inherits the JMenuItem class.

 JMenuBar(): Creates a new MenuBar.

 JMenu(): Creates a new Menu with no text.

 JMenu(String name): Creates a new Menu with a specified name.

 JMenu(String name, boolean b): Creates a new Menu with a specified name and
boolean value

1
PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY
6
Commonly used methods:

 add(JMenu c): Adds menu to the menu bar. Adds JMenu object to the Menu bar.

 add(Component c): Add component to the end of JMenu

 add(Component c, int index): Add component to the specified index of JMenu

 add(JMenuItem menuItem): Adds menu item to the end of the menu.

 add(String s): Creates a menu item with a specified string and appends it to the end of
the menu.

 getItem(int index): Returns the specified menuitem at the given index

Example:

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");
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);

1
PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY
7
1
PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY
8

You might also like