KEMBAR78
Java Swing | PDF | Computer Programming | Computing
0% found this document useful (0 votes)
6 views51 pages

Java Swing

Uploaded by

xyzp9702
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)
6 views51 pages

Java Swing

Uploaded by

xyzp9702
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/ 51

Course Title: Advanced JAVA Programming Course Code: 4351603

Advanced JAVA Programming

GOVERNMENT POLYTECHINC
HIMATNAGAR

DEPARTMENT OF INFORMATION TECHNOLOGY

JAVA SWING [CO1]

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Java Swing [CO1]


AWT and Swing are used to develop window-based applications in Java. Awt is an abstract
window toolkit that provides various component classes like Label, Button, TextField, etc., to
show window components on the screen. All these classes are part of the Java.awt package.

The javax.swing API provides all the component classes like JButton, JTextField, JCheckbox,
JMenu, etc.

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.

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.

What is JFC
JFC stands for Java Foundation Classes. It is a rich and comprehensive set of GUI components
and services that simplify the development and deployment of desktop, client-side, and internet
applications. It is a superset that contains AWT. JFC extends AWT by adding many components
and services that are as follows:

API/ Feature Description

Swing GUI It includes everything from buttons to split panes to tables. Many
Components components are capable of sorting, printing, and drag and drop, to name a
few of the supported features.

Pluggable Look-and- The look and feel of Swing applications is pluggable, allowing a choice of
Feel Support look and feel. For example, the same program can use either the Java or the
Windows look and feel. Additionally, the Java platform supports the GTK +
look and feel, which makes hundreds of existing looks and feels available to
Swing programs. Many more look-and-feel packages are available from
various sources.

Accessibility API It is a part of JFC that works with alternate input and output devices. It
enables assistive technologies, such as screen readers, screen magnifiers, and
Braille terminals, to get information from the UI.

Java 2D API It enables developers to easily incorporate high-quality 2D graphics, text,


and images in applications and applets. Java 2D includes extensive APIs for
generating and sending high-quality output to printing devices.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Internationalization It allows developers to build applications that can interact with users
worldwide in their own languages and cultural conventions. With the input
method framework, developers can build applications that accept text in
languages that use thousands of different characters, such as Japanese,
Chinese, or Korean.

Drag and Drop (DnD) Drag and Drop is one of the more common metaphors used in GUI. The user
is allowed to click and "hold" a GUI object, moving it to another window or
frame in the desktop with predictable results. It allows users to implement
droppable elements that transfer information between Java applications and
native applications. Although DnD is not part of Swing, it is crucial to a
commercial-quality application.

Advantage of JFC
 Its components are pluggable and require few lines of code.
 It retains Java qualities.
 An application that runs flawlessly on one OS runs flawlessly on another OS.
 It offers an open architecture.

Difference between AWT and Swing


There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing

1) AWT components are platform- Java swing components are platform-


dependent. 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


Swing. components such as 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.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

1.3 Swing Components:


Hierarchy of Java Swing classes
The hierarchy of java swing API is given below.

Commonly used Methods of Component class


The methods of Component class are widely used in java swing that is given below.

Method Description

public void add(Component c) add a component on another component.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

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.

Simple Java Swing Example


Let's see a simple swing example where we are creating one button and adding it on the JFrame
object inside the main() method.

File: FirstSwingExample.java

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
}
}

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Example of Swing by Association inside constructor


We can also write all the codes of creating JFrame, JButton and method call inside the java
constructor.

File: Simple.java

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

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

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


We can also inherit the JFrame class, so there is no need to create the instance of JFrame class
explicitly.

File: Simple2.java

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();
}}

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

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.

JButton class declaration


Let's see the declaration for javax.swing.JButton class.

public class JButton extends AbstractButton implements Accessible

Commonly used Constructors:


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.

Java JButton Example


import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

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

Output:

Example of displaying image on the button:


import javax.swing.*;
public class ButtonExample{
ButtonExample(){
JFrame f=new JFrame("Button Example");
JButton b=new JButton(new ImageIcon("D:\\icon.png"));
b.setBounds(100,100,100, 40);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

public static void main(String[] args) {


new ButtonExample();
}
}

Output:

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.

JLabel class declaration


Let's see the declaration for javax.swing.JLabel class.

public class JLabel extends JComponent implements SwingConstants, Accessible

Commonly used Constructors:


Constructor Description

JLabel() Creates a JLabel instance with no image and with an empty string for the title.

JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specified image.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

JLabel(String s, Icon i, Creates a JLabel instance with the specified text, image, and horizontal alignment.
int
horizontalAlignment)

Commonly used Methods:


Methods Description

String getText() t returns the text string that a label displays.

void setText(String text) It defines the single line of text this component will display.

void setHorizontalAlignment(int alignment) It sets the alignment of the label's contents along the X axis.

Icon getIcon() It returns the graphic image that the label displays.

int getHorizontalAlignment() It returns the alignment of the label's contents along the X axis.

Java JLabel Example


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

Output:

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

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.

JTextField class declaration


Let's see the declaration for javax.swing.JTextField class.

public class JTextField extends JTextComponent implements SwingConstants

Commonly used Constructors:


Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized with the specified text.

JTextField(String text, int columns) Creates a new TextField initialized with the specified text and columns.

JTextField(int columns) Creates a new empty TextField with the specified number of columns.

Commonly used Methods:


Methods Description

void addActionListener(ActionListener l) It is used to add the specified action listener to receive action
events from this textfield.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Action getAction() It returns the currently set Action for this ActionEvent source, or
null if no Action is set.

void setFont(Font f) It is used to set the current font.

void It is used to remove the specified action listener so that it no


removeActionListener(ActionListener l) longer receives action events from this textfield.

Java JTextField Example


import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}}

Output:

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

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

JTextArea class declaration


Let's see the declaration for javax.swing.JTextArea class.

public class JTextArea extends JTextComponent

Commonly used Constructors:


Constructor Description

JTextArea() Creates a text area that displays no text initially.

JTextArea(String s) Creates a text area that displays specified text initially.

JTextArea(int row, int column) Creates a text area with the specified number of rows and columns that
displays no text initially.

JTextArea(String s, int row, int Creates a text area with the specified number of rows and columns that
column) displays specified text.

Commonly used Methods:


Methods Description

void setRows(int rows) It is used to set specified number of rows.

void setColumns(int cols) It is used to set specified number of columns.

void setFont(Font f) It is used to set the specified font.

void insert(String s, int position) It is used to insert the specified text on the specified position.

void append(String s) It is used to append the given text to the end of the document.

Java JTextArea Example


import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

JTextArea area=new JTextArea("Welcome to javatpoint");


area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}}

Output:

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.

JCheckBox class declaration


Let's see the declaration for javax.swing.JCheckBox class.

public class JCheckBox extends JToggleButton implements Accessible

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Commonly used Constructors:


Constructor Description

JJCheckBox() Creates an initially unselected check box button with no text, no icon.

JChechBox(String s) Creates an initially unselected check box with text.

JCheckBox(String text, boolean Creates a check box with text and specifies whether or not it is
selected) initially selected.

JCheckBox(Action a) Creates a check box where properties are taken from the Action
supplied.

Commonly used Methods:


Methods Description

AccessibleContext It is used to get the AccessibleContext associated with this


getAccessibleContext() JCheckBox.

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

Java JCheckBox Example


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

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

}}

Output:

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.

It should be added in ButtonGroup to select one radio button only.

JRadioButton class declaration


Let's see the declaration for javax.swing.JRadioButton class.

public class JRadioButton extends JToggleButton implements Accessible

Commonly used Constructors:


Constructor Description

JRadioButton() Creates an unselected radio button with no text.

JRadioButton(String s) Creates an unselected radio button with specified text.

JRadioButton(String s, boolean selected) Creates a radio button with the specified text and selected status.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Commonly used Methods:


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.

Java JRadioButton Example


import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}

Output:

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

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.

JComboBox class declaration


Let's see the declaration for javax.swing.JComboBox class.

public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, ActionList


ener, Accessible

Commonly used Constructors:


Constructor Description

JComboBox() Creates a JComboBox with a default data model.

JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified array.

JComboBox(Vector<?> items) Creates a JComboBox that contains the elements in the specified Vector.

Commonly used Methods:


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.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

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.

Java JComboBox Example


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();
}
}

Output:

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Java JMenuBar, JMenu and JMenuItem


The JMenuBar class is used to display menu bar 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.

JMenuBar class declaration


public class JMenuBar extends JComponent implements MenuElement, Accessible

JMenu class declaration


public class JMenu extends JMenuItem implements MenuElement, Accessible

JMenuItem class declaration


public class JMenuItem extends AbstractButton implements Accessible, MenuElement

Java JMenuItem and JMenu Example


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");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

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();
}}

Output:

1.4 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:

1. java.awt.BorderLayout

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

1. FlowLayout
FlowLayout is a simple layout manager that arranges components in a row, left to right,
wrapping to the next line as needed. It is ideal for scenarios where components need to maintain
their natural sizes and maintain a flow-like structure.

FlowLayoutExample.java

import javax.swing.*;
import java.awt.*;
public class FlowLayoutExample {
public static void main(String[] args) {
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"));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Output:

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

2. 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.

BorderLayoutExample.java

import javax.swing.*;
import java.awt.*;
public class BorderLayoutExample {
public static void main(String[] args) {
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);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Output:

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

3. 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.

GridLayoutExample.java

import javax.swing.*;
import java.awt.*;
public class GridLayoutExample {
public static void main(String[] args) {
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));
}
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Output:

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

4. 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.

CardLayoutExample.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CardLayoutExample {
public static void main(String[] args) {
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");
JButton button3 = new JButton("Card 3");
cardPanel.add(button1, "Card 1");
cardPanel.add(button2, "Card 2");
cardPanel.add(button3, "Card 3");
frame.add(cardPanel);

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button1.addActionListener(e -> cardLayout.show(cardPanel, "Card 2"));
button2.addActionListener(e -> cardLayout.show(cardPanel, "Card 3"));
button3.addActionListener(e -> cardLayout.show(cardPanel, "Card 1"));
}
}

Output:

5. GroupLayout
GroupLayout is a versatile and complex layout manager that provides precise control over the
positioning and sizing of components. It arranges components in a hierarchical manner using
groups. GroupLayout is commonly used in GUI builders like the one in NetBeans IDE.

GroupLayoutExample.java

import javax.swing.*;
public class GroupLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("GroupLayout Example");
JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
panel.setLayout(layout);
JButton button1 = new JButton("Button 1");

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

JButton button2 = new JButton("Button 2");


layout.setHorizontalGroup(layout.createSequentialGroup()
.addComponent(button1)
.addComponent(button2));
layout.setVerticalGroup(layout.createParallelGroup()
.addComponent(button1)
.addComponent(button2));
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Output:

6. GridBagLayout
GridBagLayout is a powerful layout manager that allows you to create complex layouts by
specifying constraints for each component. It arranges components in a grid, but unlike
GridLayout, it allows components to span multiple rows and columns and have varying sizes.

GridBagLayoutExample.java

import javax.swing.*;
import java.awt.*;
public class GridBagLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("GridBagLayout Example");
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
JButton button1 = new JButton("Button 1");

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

JButton button2 = new JButton("Button 2");


constraints.gridx = 0;
constraints.gridy = 0;
panel.add(button1, constraints);
constraints.gridx = 1;
panel.add(button2, constraints);
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Output:

Conclusion
Java offers a variety of layout managers to cater to different design requirements. By choosing
the appropriate layout manager, we can create visually appealing and organized GUIs that
enhance the user experience. Whether we need a linear flow, grid arrangement, region-based
distribution, or card-based navigation, Java's layout managers have we covered. Experiment with
these layout managers to create stunning and user-friendly applications.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Event and Listener (Java Event Handling)


Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The
java.awt.event package provides many event classes and Listener interfaces for event handling.

Java Event classes and Listener interfaces


Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling


Following steps are required to perform event handling:

1. Register the component with the Listener

Registration Methods
For registering the component with the Listener, many classes provide the registration methods.
For example:

o Button
o public void addActionListener(ActionListener a){}
o MenuItem

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

o public void addActionListener(ActionListener a){}


o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}

o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

Java 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().

actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on the registered
component.

public abstract void actionPerformed(ActionEvent e);

How to write ActionListener


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 ActionListener

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

2) Register the component with the Listener:

component.addActionListener(instanceOfListenerclass);

3) Override the actionPerformed() method:

public void actionPerformed(ActionEvent e){


//Write the code here
}

Java ActionListener Example: On Button click

import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);

//register listener
b.addActionListener(this);//passing current instance

//add components and set size, layout and visibility


add(b);
add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

new AEvent();
}
}

NOTE: public void setBounds(int xaxis, int yaxis, int width, int height); have been used in
the above example that sets the position of the component it may be button, textfield etc.

Java ActionListener Example: Using Anonymous class


We can also use the anonymous class to implement the ActionListener. It is the shorthand way,
so you do not need to follow the 3 steps:

b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
});

Let us see the full code of ActionListener using anonymous class.

import java.awt.*;
import java.awt.event.*;
public class ActionListenerExample {
public static void main(String[] args) {
Frame f=new Frame("ActionListener Example");

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

final TextField tf=new TextField();


tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);

b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Output:

Java MouseListener Interface


The Java MouseListener is notified whenever you change the state of mouse. It is notified
against MouseEvent. The MouseListener interface is found in java.awt.event package. It has five
methods.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Methods of MouseListener interface


The signature of 5 methods found in MouseListener interface are given below:

1. public abstract void mouseClicked(MouseEvent e);


2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);

Java MouseListener Example


import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);

l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}

Output:

Java MouseListener Example 2


import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample2 extends Frame implements MouseListener{
MouseListenerExample2(){
addMouseListener(this);

setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}

public static void main(String[] args) {


new MouseListenerExample2();
}
}

Output:

Java MouseMotionListener Interface


The Java MouseMotionListener is notified whenever you move or drag mouse. It is notified
against MouseEvent. The MouseMotionListener interface is found in java.awt.event package. It
has two methods.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Methods of MouseMotionListener interface


The signature of 2 methods found in MouseMotionListener interface are given below:

1. public abstract void mouseDragged(MouseEvent e);


2. public abstract void mouseMoved(MouseEvent e);

Java MouseMotionListener Example


import java.awt.*;
import java.awt.event.*;
public class MouseMotionListenerExample extends Frame implements MouseMotionListener{
MouseMotionListenerExample(){
addMouseMotionListener(this);

setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {}

public static void main(String[] args) {


new MouseMotionListenerExample();
}
}

Output:

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Java MouseMotionListener Example 2


import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class Paint extends Frame implements MouseMotionListener{
Label l;
Color c=Color.BLUE;
Paint(){
l=new Label();
l.setBounds(20,40,100,20);
add(l);

addMouseMotionListener(this);

setSize(400,400);
setLayout(null);
setVisible(true);
}

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

public void mouseDragged(MouseEvent e) {


l.setText("X="+e.getX()+", Y="+e.getY());
Graphics g=getGraphics();
g.setColor(Color.RED);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {
l.setText("X="+e.getX()+", Y="+e.getY());
}
public static void main(String[] args) {
new Paint();
}
}

Output:

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Java ItemListener Interface


The Java ItemListener is notified whenever you click on the checkbox. It is notified against
ItemEvent. The ItemListener interface is found in java.awt.event package. It has only one
method: itemStateChanged().

itemStateChanged() method
The itemStateChanged() method is invoked automatically whenever you click or unclick on the
registered checkbox component.
public abstract void itemStateChanged(ItemEvent e);

Java ItemListener Example


import java.awt.*;
import java.awt.event.*;
public class ItemListenerExample implements ItemListener{
Checkbox checkBox1,checkBox2;
Label label;
ItemListenerExample(){
Frame f= new Frame("CheckBox Example");
label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
checkBox1 = new Checkbox("C++");
checkBox1.setBounds(100,100, 50,50);
checkBox2 = new Checkbox("Java");
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.add(label);
checkBox1.addItemListener(this);
checkBox2.addItemListener(this);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
if(e.getSource()==checkBox1)

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

label.setText("C++ Checkbox: " + (e.getStateChange()==1?"checked":"unchecked"));


if(e.getSource()==checkBox2)
label.setText("Java Checkbox: " + (e.getStateChange()==1?"checked":"unchecked"));
}
public static void main(String args[])
{
new ItemListenerExample();
}
}

Output:

Java KeyListener Interface


The Java KeyListener is notified whenever you change the state of key. It is notified against
KeyEvent. The KeyListener interface is found in java.awt.event package, and it has three
methods.

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Interface declaration
Following is the declaration for java.awt.event.KeyListener interface:

public interface KeyListener extends EventListener

Methods of KeyListener interface


The signature of 3 methods found in KeyListener interface are given below:

Sr. no. Method name Description

1. public abstract void keyPressed (KeyEvent e); It is invoked when a key has been pressed.

2. public abstract void keyReleased (KeyEvent e); It is invoked when a key has been released.

3. public abstract void keyTyped (KeyEvent e); It is invoked when a key has been typed.

Methods inherited
This interface inherits methods from the following interface:

o java.awt.EventListener

Java KeyListener Example


In the following example, we are implementing the methods of the KeyListener interface.

KeyListenerExample.java

// importing awt libraries


import java.awt.*;
import java.awt.event.*;
// class which inherits Frame class and implements KeyListener interface
public class KeyListenerExample extends Frame implements KeyListener {
// creating object of Label class and TextArea class
Label l;
TextArea area;
// class constructor

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

KeyListenerExample() {
// creating the label
l = new Label();
// setting the location of the label in frame
l.setBounds (20, 50, 100, 20);
// creating the text area
area = new TextArea();
// setting the location of text area
area.setBounds (20, 80, 300, 300);
// adding the KeyListener to the text area
area.addKeyListener(this);
// adding the label and text area to the frame
add(l);
add(area);
// setting the size, layout and visibility of frame
setSize (400, 400);
setLayout (null);
setVisible (true);
}
// overriding the keyPressed() method of KeyListener interface where we set the text of the label when ke
y is pressed
public void keyPressed (KeyEvent e) {
l.setText ("Key Pressed");
}
// overriding the keyReleased() method of KeyListener interface where we set the text of the label when k
ey is released
public void keyReleased (KeyEvent e) {
l.setText ("Key Released");
}
// overriding the keyTyped() method of KeyListener interface where we set the text of the label when a ke
y is typed
public void keyTyped (KeyEvent e) {
l.setText ("Key Typed");
}
// main method
public static void main(String[] args) {

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

new KeyListenerExample();
}
}

Output:

Java KeyListener Example 2: Count Words & Characters


In the following example, we are printing the count of words and characters of the string. Here,
the string is fetched from the TextArea and uses the KeyReleased() method of KeyListener
interface.

KeyListenerExample2.java

// importing the necessary libraries


import java.awt.*;
import java.awt.event.*;
// class which inherits Frame class and implements KeyListener interface
public class KeyListenerExample2 extends Frame implements KeyListener {
// object of Label and TextArea
Label l;

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

TextArea area;
// class constructor
KeyListenerExample2() {
// creating the label
l = new Label();
// setting the location of label
l.setBounds (20, 50, 200, 20);
// creating the text area
area = new TextArea();
// setting location of text area
area.setBounds (20, 80, 300, 300);
// adding KeyListener to the text area
area.addKeyListener(this);
// adding label and text area to frame
add(l);
add(area);
// setting size, layout and visibility of frame
setSize (400, 400);
setLayout (null);
setVisible (true);
}
// even if we do not define the interface methods, we need to override them
public void keyPressed(KeyEvent e) {}
// overriding the keyReleased() method of KeyListener interface
public void keyReleased (KeyEvent e) {
// defining a string which is fetched by the getText() method of TextArea class
String text = area.getText();
// splitting the string in words
String words[] = text.split ("\\s");
// printing the number of words and characters of the string
l.setText ("Words: " + words.length + " Characters:" + text.length());
}
public void keyTyped(KeyEvent e) {}
// main method
public static void main(String[] args) {
new KeyListenerExample2();

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

}
}

Output:

Java WindowListener Interface


The Java WindowListener is notified whenever you change the state of window. It is notified
against WindowEvent. The WindowListener interface is found in java.awt.event package. It has
three methods.

WindowListener interface declaration


The declaration for java.awt.event.WindowListener interface is shown below:

public interface WindowListener extends EventListener

Methods of WindowListener interface


The signature of 7 methods found in WindowListener interface with their usage are given below:

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Sr. Method signature Description


no.

1. public abstract void windowActivated It is called when the Window is set to be an active
(WindowEvent e); Window.

2. public abstract void windowClosed It is called when a window has been closed as the result
(WindowEvent e); of calling dispose on the window.

3. public abstract void windowClosing It is called when the user attempts to close the window
(WindowEvent e); from the system menu of the window.

4. public abstract void windowDeactivated It is called when a Window is not an active Window
(WindowEvent e); anymore.

5. public abstract void windowDeiconified It is called when a window is changed from a minimized
(WindowEvent e); to a normal state.

6. public abstract void windowIconified It is called when a window is changed from a normal to a
(WindowEvent e); minimized state.

7. public abstract void windowOpened It is called when window is made visible for the first
(WindowEvent e); time.

Methods inherited by the WindowListener


This interface inherits methods from the EventListener interface.

Working of WindowListener interface


o If a class needs to process some Window events, an object should exist which can implement the
interface.
o As the object is already registered with Listener, an event will be generated on all the states of
window.
o This helps in generation of invocation of relevant method in listener's object. And then
WindowEvent is passed after invocation.

Java WindowListener Example


In the following example, we are going to implement all the method of WindowListener
interface one by one.

WindowExample.java

// importing necessary libraries of awt

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

// class which inherits Frame class and implements WindowListener interface


public class WindowExample extends Frame implements WindowListener {

// class constructor
WindowExample() {

// adding WindowListener to the frame


addWindowListener(this);
// setting the size, layout and visibility of frame
setSize (400, 400);
setLayout (null);
setVisible (true);
}
// main method
public static void main(String[] args) {
new WindowExample();
}

// overriding windowActivated() method of WindowListener interface which prints the given string when
window is set to be active
public void windowActivated (WindowEvent arg0) {
System.out.println("activated");
}

// overriding windowClosed() method of WindowListener interface which prints the given string when wi
ndow is closed
public void windowClosed (WindowEvent arg0) {
System.out.println("closed");
}

// overriding windowClosing() method of WindowListener interface which prints the given string when w
e attempt to close window from system menu

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

public void windowClosing (WindowEvent arg0) {


System.out.println("closing");
dispose();
}

// overriding windowDeactivated() method of WindowListener interface which prints the given string whe
n window is not active
public void windowDeactivated (WindowEvent arg0) {
System.out.println("deactivated");
}

// overriding windowDeiconified() method of WindowListener interface which prints the given string whe
n window is modified from minimized to normal state
public void windowDeiconified (WindowEvent arg0) {
System.out.println("deiconified");
}

// overriding windowIconified() method of WindowListener interface which prints the given string when
window is modified from normal to minimized state
public void windowIconified(WindowEvent arg0) {
System.out.println("iconified");
}

// overriding windowOpened() method of WindowListener interface which prints the given string when w
indow is first opened
public void windowOpened(WindowEvent arg0) {
System.out.println("opened");
}
}

Output:

Prepared By: Mr. Nitin K. Kanzariya


Course Title: Advanced JAVA Programming Course Code: 4351603

Prepared By: Mr. Nitin K. Kanzariya

You might also like