Java Swing
Java Swing
GOVERNMENT POLYTECHINC
HIMATNAGAR
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.
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:
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.
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.
3) AWT doesn't support pluggable look and Swing supports pluggable look and feel.
feel.
Method Description
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.
We can write the code of swing inside the main(), constructor or any other 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
}
}
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);
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();
}}
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.
Output:
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() Creates a JLabel instance with no image and with an empty string for the title.
JLabel(String s, Icon i, Creates a JLabel instance with the specified text, image, and horizontal alignment.
int
horizontalAlignment)
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.
Output:
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(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.
void addActionListener(ActionListener l) It is used to add the specified action listener to receive action
events from this textfield.
Action getAction() It returns the currently set Action for this ActionEvent source, or
null if no Action is set.
Output:
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(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.
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.
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.
JJCheckBox() Creates an initially unselected check box button with no text, no icon.
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.
}}
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.
JRadioButton(String s, boolean selected) Creates a radio button with the specified text and selected status.
Output:
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(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.
void removeAllItems() It is used to remove all the items from the list.
Output:
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.
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. java.awt.BorderLayout
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:
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:
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:
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);
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");
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");
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.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
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
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){}
actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on the registered
component.
component.addActionListener(instanceOfListenerclass);
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
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.
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
});
import java.awt.*;
import java.awt.event.*;
public class ActionListenerExample {
public static void main(String[] args) {
Frame f=new Frame("ActionListener Example");
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:
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");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
Output:
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
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) {}
Output:
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) {}
Output:
addMouseMotionListener(this);
setSize(400,400);
setLayout(null);
setVisible(true);
}
Output:
itemStateChanged() method
The itemStateChanged() method is invoked automatically whenever you click or unclick on the
registered checkbox component.
public abstract void itemStateChanged(ItemEvent e);
Output:
Interface declaration
Following is the declaration for java.awt.event.KeyListener interface:
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
KeyListenerExample.java
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) {
new KeyListenerExample();
}
}
Output:
KeyListenerExample2.java
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();
}
}
Output:
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.
WindowExample.java
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
// class constructor
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
// 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: