Java Swing
Java Swing
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.
Class Constructors
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.
java.awt. Window
java. awt. Container
java. awt. Component
java. lang. Object
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");
}
Constructor Description
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 )
{
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 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!");
}
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.
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:
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
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:
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");
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);
} }
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.
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(String s): Creates a menu item with a specified string and appends it to the end of
the menu.
Example:
1
PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY
7
1
PREPARED BY ASST PROFESSOR T. RAVISHANKAR DEPARTMENT OF INFORMATION TECHNOLOGY
8