Java Unit 4 Swing
Java Unit 4 Swing
Swing Package:
The primary package for Swing is javax.swing. It contains a comprehensive set of classes and
interfaces for building graphical user interfaces.
The key components of the javax.swing package include:
JComponents:
The JComponent class is a base class for all Swing components.
Various components, such as JButton, JTextField, JLabel, and more, extend JComponent.
Containers:
Swing provides containers like JFrame, JPanel, JDialog, and JApplet for organizing and
managing components.
Layout Managers:
Layout managers, such as FlowLayout, BorderLayout, GridLayout, and GridBagLayout,
assist in arranging components within containers.
Events and Listeners:
Swing follows the event-driven programming model. Key event-related classes include
ActionEvent, ActionListener, MouseEvent, MouseListener, etc.
Models and Renderers:
Classes like DefaultListModel, DefaultTableCellRenderer, and others support data models
and custom rendering for components like lists and tables.
Dialogs and Option Panes:
Swing provides classes like JOptionPane for creating standard dialogs (message, input,
confirm) in a consistent manner.
Menus and Toolbars:
JMenuBar, JMenu, JMenuItem, and related classes are used for creating menus and toolbars.
Pluggable Look and Feel:
UIManager class enables developers to change the look and feel of the application.
NOTE:
1. RootPane:
Purpose: The RootPane is the top-level container that holds all other Swing components
within a JFrame.
Components: It includes the ContentPane, LayeredPane, and optional decorations such as the
title bar, menu bar, and status bar.
Usage:
Developers typically interact with the RootPane indirectly through the JFrame class.
Customization of the RootPane is often done for special layout or behavior requirements.
2. LayeredPane:
Purpose: The LayeredPane is used to manage the layering or stacking of components within a
JFrame.
Components: Components added to the LayeredPane can be positioned at different layers,
allowing for overlapping and depth arrangement.
Usage:
Useful when you need to overlay components or create complex visual effects.
Components are added to specific layers using the setLayer() method.
3. ContentPane:
Purpose: The ContentPane is the primary container where application components are added
for display within a JFrame.
Components: All standard user interface components (buttons, labels, panels, etc.) are
typically added to the ContentPane.
Usage:
Most of the GUI development occurs by adding components to the ContentPane.
Layout managers are used to organize and manage the placement of components within the
ContentPane.
4. GlassPane:
Purpose: The GlassPane is an invisible pane that sits on top of all other panes and
components.
Components: Components added to the GlassPane are rendered above all other components,
intercepting mouse and keyboard events.
Usage:
Useful for creating custom overlays, modal dialogs, or blocking user input during certain
operations.
It allows developers to intercept events before they reach other components.
NOTE:
In Java Swing, the contentPane is a container where you typically add your components
(like panels, buttons, etc.) when creating a JFrame. By default, the JFrame has a content
pane, so you don't need to explicitly add it. However, if you want to be explicit, you can use
the getContentPane() method.
Containers :
JFrame , JPanel , JApplet , JDialog
2) JFrame :
JFrame Class:
JFrame is a class in the javax.swing package that represents the main window or frame of a
Swing application.
Top-Level Container:
It serves as a top-level container, providing a space to organize and display other Swing
components.
Window Features:
JFrame includes features such as a title bar, borders, and buttons for minimizing, maximizing,
and closing the window.
Extending JFrame:
To create a Swing application, developers often extend the JFrame class and customize its
behavior.
Constructor:
JFrame has several constructors, allowing customization of the frame's title, size, and other
properties.
Layout Manager:
It can use layout managers such as FlowLayout, BorderLayout, or others to manage the
arrangement of components within the frame.
Adding Components:
Other Swing components like buttons, labels, and panels can be added to a JFrame to create a
user interface.
Visibility:
The setVisible(boolean) method is used to make the frame visible or invisible.
Default Close Operation:
The setDefaultCloseOperation(int) method is used to define the default close operation when
the user clicks the close button.
Event Handling:
JFrame can handle events through various methods, including event listeners, to respond to
user interactions.
Resizing and Resizable:
Developers can set whether a JFrame is resizable or not using the setResizable(boolean)
method.
Icon Image:
The setIconImage(Image) method allows setting the icon image for the frame that appears in
the taskbar or window manager.
Layout and Design:
Developers often set the layout manager and customize the frame's appearance to create a
visually appealing user interface.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Components
private JLabel nameLabel;
private JTextField nameTextField;
private JLabel genderLabel;
private JComboBox<String> genderComboBox;
private JCheckBox subscribeCheckBox;
private JButton submitButton;
// Constructor
public SwingJFrameExample()
{
// Set the title for the JFrame
setTitle(" Jframe ");
// Create components
nameLabel = new JLabel("Enter your name:");
nameTextField = new JTextField(20);
genderLabel = new JLabel("Select your gender:");
String[] genders = {"Male", "Female", "Other"};
genderComboBox = new JComboBox<>(genders);
subscribeCheckBox = new JCheckBox("Subscribe to our newsletter");
submitButton = new JButton("Submit");
Output:
3) JApplet:
JApplet Class:
JApplet is a class in the javax.swing package that represents a Swing applet.
Applet in Swing:
An applet is a small Java program that runs within a web browser.
Extending JApplet:
To create a Swing applet, developers often extend the JApplet class.
Lifecycle Methods:
JApplet provides methods such as init(), start(), stop(), and destroy(), representing the applet's
lifecycle.
init() Method:
The init() method is used for applet initialization. It is called once when the applet is first
loaded.
start() Method:
The start() method is called when the applet becomes visible or starts running after being
paused.
stop() Method:
The stop() method is called when the applet is no longer visible or when it is paused.
destroy() Method:
The destroy() method is called when the applet is about to be unloaded.
Swing Components in Applets:
Like JFrame, JApplet can include various Swing components such as buttons, labels, and
panels.
Displaying in a Web Browser:
To display a JApplet in a web browser, an HTML file is typically used with the <applet> tag.
Swing Components in Applets:
Swing components can be added to a JApplet using the same principles as with a JFrame.
Layout Managers:
Layout managers such as FlowLayout, BorderLayout, or others can be used to organize
components within the applet.
Event Handling:
Event handling in applets in Swing applications, using listeners for user interactions.
Graphics and Drawing:
JApplet provides methods for custom drawing using the Graphics class, allowing developers
to create graphical content.
Applet Tag in HTML:
To embed a JApplet in an HTML page, the <applet> tag is used, specifying attributes like
code, width, height, and parameters.
Applet Life Cycle:
The applet life cycle is managed by the browser or applet viewer, calling the appropriate
methods at different stages.
Deprecated Usage:
While Swing applets were popular in the past, modern web development has shifted away
from using Java applets due to security concerns.
import javax.swing.JApplet;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
@Override
public void init()
{
// Initialization code (similar to a constructor)
JButton button = new JButton("Click Me!");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// Action to perform when the button is clicked
System.out.println("Button Clicked!");
}
});
add(button);
}
@Override
public void start()
{
// Called when the applet is started
}
@Override
public void stop()
{
// Called when the applet is stopped
}
@Override
public void destroy()
{
// Called when the applet is destroyed
}
}
Embedded with html :
<!DOCTYPE html>
<html>
<head>
<title>My Applet</title>
</head>
<body>
<applet code="MyApplet.class" width="300" height="200"></applet>
</body>
</html>
4) JPanel :
JPanel Class:
JPanel is a class in the javax.swing package that serves as a container to hold and organize
other Swing components.
Lightweight Container:
JPanel is a lightweight container, making it a versatile component for organizing and
grouping other Swing components.
Extending JPanel:
Developers can create custom panels by extending the JPanel class and adding their own
functionality.
Layout Managers:
JPanel can use layout managers, such as FlowLayout, BorderLayout, GridLayout, etc., to
manage the arrangement of components within the panel.
Adding Components:
Other Swing components like buttons, labels, and text fields can be added to a JPanel to
create a composite user interface.
Custom Drawing:
Developers can override the paintComponent(Graphics g) method to perform custom drawing
within a JPanel.
Event Handling:
JPanel can handle events using event listeners, allowing it to respond to user interactions or
other events.
Common Use:
JPanel is commonly used for grouping related components together, creating reusable and
modular UI elements
In Java Swing, a JPanel is a lightweight container that is typically used to organize and hold
other Swing components. However, to display a JPanel, it needs to be added to a top-level
container, such as a JFrame. A JFrame provides the main window or application frame
where Swing components, including JPanels, can be placed.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public CustomPanel()
{
// Create components
button = new JButton("Click me!");
new SwingJPanelExample();
}
}
Output:
JDIALOG:
Purpose:
A JDialog is used to create pop-up dialogs or secondary windows that can contain various
components and user interface elements.
Extending JDialog:
Developers can create custom dialog boxes by extending the JDialog class.
Modality:
A JDialog can be modal or modeless. Modal dialogs block input to other application
windows until the dialog is closed.
Title:
A JDialog can have a title that is displayed in the title bar of the window.
Close Operation:
Developers can specify the default close operation, such as DISPOSE_ON_CLOSE or
DO_NOTHING_ON_CLOSE.
Size and Position:
The size and position of a JDialog can be set using methods like setSize() and
setLocationRelativeTo().
Visibility:
The setVisible() method is used to make the dialog visible or invisible.
Event Handling:
Event handling in a JDialog is similar to that in a JFrame, using listeners for user interactions.
Parent-Child Relationship:
A JDialog can be associated with a parent component, such as another JFrame. The dialog is
typically centered relative to its parent.
Customization:
Developers can customize the appearance and behavior of a JDialog to suit the requirements
of the application.
import javax.swing.*;
import java.awt.*;
public SimpleDialogExample() {
// ContentPane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(new JLabel("This is a simple dialog."));
// Configure JDialog
setTitle("Simple Dialog Example");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setSize(250, 150);
setLocationRelativeTo(null); // Center the dialog on the screen
setModalityType(ModalityType.APPLICATION_MODAL); // Make the dialog modal
setVisible(true);
}
new SimpleDialogExample();
}
Output:
From Output :
There is no icons for minimize , maximize , hide in JDialog.
So to get all these icons JDialog need to maintain a parent-child relationship with JFrame.
import javax.swing.*;
import java.awt.*;
// Configure JDialog
setTitle("Simple Dialog Example");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setSize(250, 150);
setLocationRelativeTo(parent);
setModalityType(ModalityType.APPLICATION_MODAL); // Make the dialog modal
setVisible(true);
}
parentFrame.getContentPane().setLayout(new FlowLayout());
parentFrame.getContentPane().add(showDialogButton);
parentFrame.setLocationRelativeTo(null);
parentFrame.setVisible(true);
});
}
}
Output:
JCANVAS:
import javax.swing.*;
import java.awt.*;
class DrawingCanvas extends Canvas
{
@Override
public void paint(Graphics g)
{
// Draw on the canvas
g.setColor(Color.BLUE);
g.fillRect(50, 50, 100, 100);
g.setColor(Color.RED);
g.drawLine(200, 50, 300, 150);
}
}
public SwingJCanvas()
{
setTitle("Simple Canvas Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Output:
5. COMPONENTS IN SWINGS :
A) JBUTTON:
import javax.swing.JButton;
import javax.swing.JFrame;
setVisible(true);
}
import javax.swing.JFrame;
import javax.swing.JTextField;
setVisible(true);
}
C) JTEXTAREA :
import javax.swing.JFrame;
import javax.swing.JTextArea;
setVisible(true);
}
Output:
D) JCHECKBOX:
import javax.swing.JCheckBox;
import javax.swing.JFrame;
Output:
E) JRADIO BUTTON:
import javax.swing.JRadioButton;
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.*;
public class JRadioButtonExample extends JFrame
{
public JRadioButtonExample()
{
setTitle("JRadioButton Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new FlowLayout());
setVisible(true);
}
Output:
F) JCOMBOBOX:
import javax.swing.JComboBox;
import javax.swing.JFrame;
setVisible(true);
}
Output:
When click on the scrollbar it will drag the options , then when select the option2 it
displayed.
G) JLABEL:
import javax.swing.JFrame;
import javax.swing.JLabel;
setVisible(true);
}
Output:
H) JFILECHOOSER
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
public JFileChooserExample()
{
super("JFileChooser Example");
Output:
When click on the “open file chooser “
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public JFileChooserExample2() {
super("JFileChooser Example");
// Create a JTextArea
textArea = new JTextArea();
textArea.setEditable(false);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
readFile(selectedFile);
}
}
textArea.setText(content.toString());
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "Error reading the file", "Error",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
new JFileChooserExample2();
}
}
Output:
I) JCOLORCHOOSER:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public JColorChooserExample()
{
super("JColorChooser Example");
Output:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TextFieldColorChooserExample extends JFrame {
public TextFieldColorChooserExample() {
super("TextField Color Chooser Example");
// Create a JTextField
textField = new JTextField("Type Here");
textField.setPreferredSize(new Dimension(200, 30));
Output:
J) JTABLE:
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public JTableExample()
{
super("JTable Example");
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
Output:
L) 6) JLIST:
import javax.swing.JList;
import javax.swing.JFrame;
setVisible(true);
}
import javax.swing.*;
// Create a JTextArea
JTextArea textArea = new JTextArea();
textArea.setText("This is a JTextArea with a JScrollPane.\nTry scrolling!");
N) 8) SPLLITPANE:
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
public SwingJSplitPane()
{
setTitle("JSplitPane Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] items = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7",
"Item 8"};
itemList = new JList<>(items);
// Create a JSplitPane with the JList on the left and JTextArea on the right
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new
JScrollPane(itemList), new JScrollPane(textArea));
splitPane.setDividerLocation(150); // Set initial divider location
getContentPane().add(splitPane);
setVisible(true);
}
Output:
O) 9) JTABBEDPANE:
import javax.swing.*;
import java.awt.*;
getContentPane().setLayout(new BorderLayout());
getContentPane().add(tabbedPane, BorderLayout.CENTER);
setVisible(true);
}
private void showMessage(String message) {
JOptionPane.showMessageDialog(this, message, "Message",
JOptionPane.INFORMATION_MESSAGE);
}
Output:
import javax.swing.*;
import java.awt.*;
public class SimpleDialogExample2 extends JDialog
{
// Configure JDialog
setTitle("Simple Dialog Example");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setSize(250, 150);
setLocationRelativeTo(parent);
setModalityType(ModalityType.APPLICATION_MODAL); // Make the dialog modal
setVisible(true);
}
parentFrame.setLocationRelativeTo(null);
parentFrame.setVisible(true);
});
}
}
Output:
JOptionPane in Swing:
1. Usage:
JOptionPane is a class in Swing that provides a standard way to prompt users
for input or inform them about an event in a GUI.
It simplifies the creation and display of dialog boxes with consistent
appearance.
2. Creating Dialog Boxes:
You can create various types of dialog boxes, including message, input,
confirm, and option dialogs.
JOptionPane.showMessageDialog(null, "Hello, this is a message
dialog", "Message", JOptionPane.INFORMATION_MESSAGE);
3. Message Types:
JOptionPane supports different message types such as
INFORMATION_MESSAGE, WARNING_MESSAGE, ERROR_MESSAGE,
QUESTION_MESSAGE, and PLAIN_MESSAGE .
4. Input Dialog:
JOptionPane.showInputDialog creates an input dialog that prompts the user
for input.
String userInput = JOptionPane.showInputDialog("Enter your name:"); ;
5. Confirm Dialog:
JOptionPane.showConfirmDialog creates a dialog with options like
Yes/No/Cancel and returns the user's choice.
int result = JOptionPane.showConfirmDialog(null, "Do you want to
proceed?", "Confirmation", JOptionPane.YES_NO_CANCEL_OPTION);
6. Custom Buttons:
You can customize buttons in option dialogs using an array of objects
representing the button names.
Object[] options = {"Option 1", "Option 2", "Option 3"};
int result = JOptionPane.showOptionDialog(null, "Choose an option",
"Custom Buttons", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
7. Icons:
You can display icons in JOptionPane dialogs to visually represent the type of
message.
.ERROR_MESS JOptionPane.showMessageDialog(null, "Error Message",
"Error", JOptionPane.ERROR_MESSAGE); AGE);
8. Custom Icons:
Custom icons can be added to dialogs using ImageIcon or other Icon
implementations.
ImageIcon customIcon = new ImageIcon("path/to/custom-icon.png");
JOptionPane.showMessageDialog(null, "Custom Icon Message",
"Custom Icon", JOptionPane.INFORMATION_MESSAGE, customIcon);
9. Default Button:
You can set the default button in a dialog, which is activated when the user
presses Enter.
int result = JOptionPane.showConfirmDialog(null, "Choose Yes or No",
"Default Button", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null,
JOptionPane.YES_OPTION);
10. Option Dialog Return Values:
The return value of an option dialog depends on the user's choice and can be
used to determine the selected option.
11. if (result == JOptionPane.YES_OPTION) {
12. // User chose Yes
13. } else if (result == JOptionPane.NO_OPTION) {
14. // User chose No
15. } else if (result == JOptionPane.CANCEL_OPTION) {
16. // User chose Cancel