KEMBAR78
Updated Module 3 | PDF | Graphical User Interfaces | Computing
0% found this document useful (0 votes)
20 views43 pages

Updated Module 3

The document provides an introduction to Swing, a GUI toolkit in Java that enhances the capabilities of the earlier AWT by offering lightweight components, a pluggable look-and-feel, and support for the MVC architecture. It details key features, basic components, and the structure of a simple Swing application, emphasizing the importance of components and containers in building user interfaces. Additionally, it explains the origins of Swing and its relationship with AWT, highlighting its advantages in creating consistent and customizable interfaces across platforms.

Uploaded by

4al22cs128
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)
20 views43 pages

Updated Module 3

The document provides an introduction to Swing, a GUI toolkit in Java that enhances the capabilities of the earlier AWT by offering lightweight components, a pluggable look-and-feel, and support for the MVC architecture. It details key features, basic components, and the structure of a simple Swing application, emphasizing the importance of components and containers in building user interfaces. Additionally, it explains the origins of Swing and its relationship with AWT, highlighting its advantages in creating consistent and customizable interfaces across platforms.

Uploaded by

4al22cs128
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/ 43

Module 3

Introducing Swing: The Origin of Swing, Swing Is Built on AWT, Two Key Swing Features, The MVC
Connection, Components and Containers, The Swing Packages, A Simple Swing Application, Event
Handling, Painting in Swing.
Exploring Swing : JLabel and ImageIcon,JTextField,The Swing Buttons-JButton, JToggleButton,
Check Boxes, Radio Buttons

Text Book 1: Ch 32 and Ch. 33

Introduction to Swing in Java

Swing is a powerful and flexible GUI (Graphical User Interface) toolkit in Java that provides a
richer set of components than the earlier AWT (Abstract Window Toolkit). It is part of the Java
Foundation Classes (JFC) and allows developers to create window-based applications with an easier
and more visually appealing interface.

Here are some key features and concepts related to Swing in Java:

Key Features of Swing:

Lightweight Components:

Swing components are lightweight, meaning they are drawn entirely in Java rather than relying on the
native system’s GUI components. This provides a consistent look and feel across different platforms.
Pluggable Look and Feel:

Swing supports a pluggable look-and-feel system that allows developers to change the appearance of
their applications dynamically. You can choose from several built-in themes or create your own.
Rich Set of Components:

Swing provides a wide variety of components, including buttons, labels, text fields, tables, trees, and
more. This allows developers to create complex user interfaces.

Event Handling:

Swing includes a robust event handling mechanism, which lets developers respond to user interactions
(like clicks, keyboard input, etc.) easily using listeners.

Customizable and Extendable:

Swing components can be easily customized and extended to create new components that fit specific
application needs.

Support for MVC Architecture:

Swing follows the Model-View-Controller (MVC) design pattern, allowing for better separation
between the data (model), user interface (view), and the control logic (controller).
Basic Components of Swing:
JFrame: The main window that holds all other Swing components.
JPanel: A generic container used to organize components within a JFrame.
JButton: A clickable button that can perform actions.
JLabel: Displays a short string or an image icon.
JTextField: Allows for single-line text input.
JTextArea: Allows for multi-line text input.
JComboBox: A dropdown list from which users can select an option.
JMenuBar: A menu bar containing menus that can have items and sub-items.

Example of a Simple Swing Program:

Here's a basic Swing application that creates a window with a button and a label.

package Swings;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SimpleSwingApp {


public static void main(String[] args) {
// Create a new frame
JFrame frame = new JFrame("Simple Swing Application");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a button
JButton button = new JButton("Click Me!");

// Create a label
JLabel label = new JLabel("Welcome to Swing!");

// Add action listener to the button


button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText("Button Clicked!");
}
});

// Add the button and label to the frame


JPanel panel = new JPanel();
panel.add(button);
panel.add(label);
frame.add(panel);

// Set frame visibility


frame.setVisible(true);
}
}

o/p

The Origins of Swing

Swing did not exist in the early days of Java. Rather, it was a response to deficiencies present
in Java’s original GUI subsystem: the Abstract Window Toolkit. The AWT defines a basic set
of controls, windows, and dialog boxes that support a usable, but limited graphical interface.
One reason for the limited nature of the AWT is that it translates its various visual components
into their corresponding, platform-specific equivalents, or peers. This means that the look
and feel of a component is defined by the platform, not by Java. Because the AWT components
use native code resources, they are referred to as heavyweight.
The use of native peers led to several problems. First, because of variations between
operating systems, a component might look, or even act, differently on different platforms.
This potential variability threatened the overarching philosophy of Java: write once, run
anywhere. Second, the look and feel of each component was fixed (because it is defined by
the platform) and could not be (easily) changed. Third, the use of heavyweight components
caused some frustrating restrictions. For example, a heavyweight component was always
opaque.
Not long after Java’s original release, it became apparent that the limitations and
restrictions present in the AWT were sufficiently serious that a better approach was needed.
The solution was Swing. Introduced in 1997, Swing was included as part of the Java Foundation
Classes (JFC). Swing was initially available for use with Java 1.1 as a separate library. However,
beginning with Java 1.2, Swing (and the rest of the JFC) was fully integrated into Java.

Swing Is Built on the AWT

Before moving on, it is necessary to make one important point: although Swing eliminates
a number of the limitations inherent in the AWT, Swing does not replace it. Instead, Swing is
built on the foundation of the AWT. This is why the AWT is still a crucial part of Java. Swing
also uses the same event handling mechanism as the AWT. Therefore, a basic understanding
of the AWT and of event handling is required to use Swing. (The AWT is covered in
Chapters 25 and 26. Event handling is described in Chapter 24.)
Two Key Swing Features
As just explained, Swing was created to address the limitations present in the AWT. It does
this through two key features: lightweight components and a pluggable look and feel.
Together they provide an elegant, yet easy-to-use solution to the problems of the AWT.
More than anything else, it is these two features that define the essence of Swing. Each
is examined here.

Swing Components Are Lightweight


With very few exceptions, Swing components are lightweight. This means that they are
written entirely in Java and do not map directly to platform-specific peers. Thus,
lightweight components are more efficient and more flexible. Furthermore,
because lightweight components do not translate into native peers, the look and feel
of each component is determined by Swing, not by the underlying operating system. As
a result, each component will work in a consistent manner across all platforms.

Swing Supports a Pluggable Look and Feel


Swing supports a pluggable look and feel (PLAF). Because each Swing component is rendered
by Java code rather than by native peers, the look and feel of a component is under the
control of Swing. This fact means that it is possible to separate the look and feel of a
component from the logic of the component, and this is what Swing does. Separating out
the look and feel provides a significant advantage: it becomes possible to change the way
that a component is rendered without affecting any of its other aspects. In other words, it is
possible to “plug in” a new look and feel for any given component without creating any side
effects in the code that uses that component. Moreover, it becomes possible to define entire
sets of look-and-feels that represent different GUI styles. To use a specific style, its look and
feel is simply “plugged in.” Once this is done, all components are automatically rendered
using that style.
Pluggable look-and-feels offer several important advantages. It is possible to define a
look and feel that is consistent across all platforms. Conversely, it is possible to create a look
and feel that acts like a specific platform. For example, if you know that an application will
be running only in a Windows environment, it is possible to specify the Windows look and
feel. It is also possible to design a custom look and feel. Finally, the look and feel can be
changed dynamically at run time.
Java 8 provides look-and-feels, such as metal and Nimbus, that are available to all Swing
users. The metal look and feel is also called the Java look and feel. It is platform-independent
and available in all Java execution environments. It is also the default look and feel. Windows
environments also have access to the Windows look and feel. This book uses the default
Java look and feel (metal) because it is platform independent.

The MVC connection

In general, a visual component is a composite of three distinct aspects:


• The way that the component looks when rendered on the screen
• The way that the component reacts to the user
• The state information associated with the component
No matter what architecture is used to implement a component, it must implicitly contain these three
parts. Over the years, one component architecture has proven itself to be exceptionally effective:
Model-View-Controller, or MVC for short.

The MVC architecture is successful because each piece of the design corresponds to an aspect of a
component. In MVC terminology, the model corresponds to the state information associated with the
component. For example, in the case of a check box, the model contains a field that indicates if the box
is checked or unchecked. The view determines how the component is displayed on the screen,
including any aspects of the view that are affected by the current state of the model. The controller
determines how the component reacts to the user. For example, when the user clicks a check box, the
controller reacts by changing the model to reflect the user’s choice (checked or unchecked). This then
results in the view being updated. By separating a component into a model, a view, and a controller, the
specific implementation of each can be changed without affecting the other two. For instance,
different view implementations can render the same component in different ways without affecting the
model or the controller.

Although the MVC architecture and the principles behind it are conceptually sound,
the high level of separation between the view and the controller is not beneficial for Swing
components. Instead, Swing uses a modified version of MVC that combines the view and
the controller into a single logical entity called the UI delegate. For this reason, Swing’s
approach is called either the Model-Delegate architecture or the Separable Model architecture.
Therefore, although Swing’s component architecture is based on MVC, it does not use a
classical implementation of it.

Swing’s pluggable look and feel is made possible by its Model-Delegate architecture.
Because the view (look) and controller (feel) are separate from the model, the look and
feel can be changed without affecting how the component is used within a program.
Conversely, it is possible to customize the model without affecting the way that the
component appears on the screen or responds to user input.
To support the Model-Delegate architecture, most Swing components contain two
objects. The first represents the model. The second represents the UI delegate. Models are
defined by interfaces. For example, the model for a button is defined by the ButtonModel
interface. UI delegates are classes that inherit ComponentUI. For example, the UI delegate
for a button is ButtonUI. Normally, your programs will not interact directly with the UI
delegate.

Components and Containers

A Swing GUI consists of two key items: components and containers. However, this distinction is
mostly conceptual because all containers are also components. The difference between the two is
found in their intended purpose: As the term is commonly used, a component is an
independent visual control, such as a push button or slider. A container holds a group of
components. Thus, a container is a special type of component that is designed to hold
other components. Furthermore, in order for a component to be displayed, it must be held
within a container. Thus, all Swing GUIs will have at least one container. Because containers
are components, a container can also hold other containers. This enables Swing to define
what is called a containment hierarchy, at the top of which must be a top-level container.
Let’s look a bit more closely at components and containers.
Components

In general, Swing components are derived from the JComponent class. (The only exceptions
to this are the four top-level containers, described in the next section.) JComponent provides
the functionality that is common to all components. For example, JComponent supports the
pluggable look and feel. JComponent inherits the AWT classes Container and Component.
Thus, a Swing component is built on and compatible with an AWT component.
All of Swing’s components are represented by classes defined within the package
javax.swing. The following table shows the class names for Swing components (including
those used as containers)

Notice that all component classes begin with the letter J. For example, the class for a label
is JLabel; the class for a push button is JButton; and the class for a scroll bar is JScrollBar.
Containers

Swing defines two types of containers. The first are top-level containers: JFrame, JApplet,
JWindow, and JDialog. These containers do not inherit JComponent. They do, however,
inherit the AWT classes Component and Container. Unlike Swing’s other components,
which are lightweight, the top-level containers are heavyweight. This makes the top-level
containers a special case in the Swing component library.
As the name implies, a top-level container must be at the top of a containment hierarchy.
A top-level container is not contained within any other container. Furthermore, every
containment hierarchy must begin with a top-level container. The one most commonly
used for applications is JFrame. The one used for applets is JApplet.

The second type of containers supported by Swing are lightweight containers. Lightweight
containers do inherit JComponent. An example of a lightweight container is JPanel, which
is a general-purpose container. Lightweight containers are often used to organize and manage
groups of related components because a lightweight container can be contained within
another container. Thus, you can use lightweight containers such as JPanel to create
subgroups of related controls that are contained within an outer container.

The Top-Level Container Panes

Each top-level container defines a set of panes. At the top of the hierarchy is an instance
of JRootPane. JRootPane is a lightweight container whose purpose is to manage the other
panes. It also helps manage the optional menu bar. The panes that comprise the root pane
are called the glass pane, the content pane, and the layered pane.

The glass pane is the top-level pane. It sits above and completely covers all other panes.
By default, it is a transparent instance of JPanel. The glass pane enables you to manage
mouse events that affect the entire container (rather than an individual control) or to paint
over any other component, for example. In most cases, you won’t need to use the glass
pane directly, but it is there if you need it.

The layered pane is an instance of JLayeredPane. The layered pane allows components
to be given a depth value. This value determines which component overlays another. (Thus,
the layered pane lets you specify a Z-order for a component, although this is not something
that you will usually need to do.) The layered pane holds the content pane and the (optional)
menu bar.
Although the glass pane and the layered panes are integral to the operation of a top-level
container and serve important purposes, much of what they provide occurs behind the scene.
The pane with which your application will interact the most is the content pane, because
this is the pane to which you will add visual components. In other words, when you add a
component, such as a button, to a top-level container, you will add it to the content pane.
By default, the content pane is an opaque instance of JPanel.

The Swing Packages

Swing is a very large subsystem and makes use of many packages. At the time of this writing,
these are the packages defined by Swing.

The main package is javax.swing. This package must be imported into any program that
uses Swing. It contains the classes that implement the basic Swing components, such as
push buttons, labels, and check boxes.

A Simple Swing Application

Swing programs differ from both the console-based programs and the AWT-based programs
shown earlier in this book. For example, they use a different set of components and a different
container hierarchy than does the AWT. Swing programs also have special requirements that
relate to threading. The best way to understand the structure of a Swing program is to work
through an example. There are two types of Java programs in which Swing is typically used.
The first is a desktop application. The second is the applet. This section shows how to create
a Swing application. The creation of a Swing applet is described later in this chapter.
Although quite short, the following program shows one way to write a Swing
application. In the process, it demonstrates several key features of Swing. It uses two Swing
components: JFrame and JLabel. JFrame is the top-level container that is commonly used
for Swing applications. JLabel is the Swing component that creates a label, which is a
component that displays information. The label is Swing’s simplest component because
it is passive. That is, a label does not respond to user input. It just displays output. The
program uses a JFrame container to hold an instance of a JLabel. The label displays a
short text message.

package Swings;

import java.awt.Color;
import java.awt.Font;

//A simple Swing application.


import javax.swing.*;
class SwingExample {
SwingExample () {
//Create a new JFrame container.
JFrame jfrm = new JFrame("A Simple Swing Application");
//jfrm.setFont("Serif",Font.BOLD,18);

//label = new JLabel("A label"); label.setFont(new Font("Serif", Font.PLAIN, 14));


//Give the frame an initial size.
jfrm.setSize(275, 100);
//Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create a text-based label.
JLabel jlab = new JLabel(" Hello! VI B , Welcome to Swing Programming!");
// set properties for label
jlab.setFont(new Font("Verdana", Font.PLAIN,32));
jlab.setForeground(new Color(0,0,255));

//Add the label to the content pane.


jfrm.add(jlab);
//Display the frame.
jfrm.setVisible(true);
}
public static void main(String args[]) {
//Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SwingExample();
}
});
}
}
Event Handling

The event handling mechanism used by Swing is the same as that used by the AWT. This approach is
called the delegation event model, and In many cases, Swing uses the same events as does the AWT,
and these events are packaged in java.awt.event. Events specific to Swing are stored in
javax.swing.event.

package Swings;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ButtonExample{
JLabel l1;
ButtonExample(){
JFrame f=new JFrame("Button Example");

l1=new JLabel();
l1.setBounds(50,50, 700,100);
l1.setFont(new Font("Lucida Calligraphy",Font.BOLD,60));

JButton b1=new JButton(" India ");


JButton b2=new JButton(" Srilanka ");

b1.setBounds(100,200,100, 100);

b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
l1.setText("India is pressed");
}
});

b2.setBounds(400,200,100, 100);
b2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
l1.setText("SriLanka is pressed");
}
});
f.add(b1);
f.add(b2);
f.add(l1);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ButtonExample();
}
}

A Paint Example
Here is a program that puts into action the preceding discussion. It creates a class called PaintPanel that
extends JPanel. The program then uses an object of that class to display lines whose endpoints have
been generated randomly. Sample output is shown in Figure

package Swings;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

// This class extends JPanel and overrides paintComponent()


// to plot random lines in the panel
class PaintPanel extends JPanel {
private Insets ins; // holds the panel's insets
private Random rand; // used to generate random numbers

// Construct a panel
PaintPanel() {
// Put a border around the panel
setBorder(BorderFactory.createLineBorder(Color.RED, 5));
rand = new Random();
}

// Override the paintComponent() method


@Override
protected void paintComponent(Graphics g) {
// Always call the superclass method first
super.paintComponent(g);

int x, y, x2, y2;

// Get the height and width of the component


int height = getHeight();
int width = getWidth();

// Get the insets


ins = getInsets();

// Draw ten lines whose endpoints are randomly generated


for(int i = 0; i < 10; i++) {
// Obtain random coordinates that define
// the endpoints of each line
x = rand.nextInt(width - ins.left);
y = rand.nextInt(height - ins.bottom);
x2 = rand.nextInt(width - ins.left);
y2 = rand.nextInt(height - ins.bottom);

// Draw the line


g.drawLine(x, y, x2, y2);
}
}
}

// Demonstrate painting directly onto a panel


public class PaintDemo {
private JLabel jlab;
private PaintPanel pp;
private JFrame jfrm;

public PaintDemo() {
// Create a new JFrame container
jfrm = new JFrame("Paint Demo");

// Give the frame an initial size


jfrm.setSize(200, 150);

// Terminate the program when the user closes the application


jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create the panel that will be painted
pp = new PaintPanel();

// Add the panel to the content pane. Because the default


// border layout is used, the panel will automatically be
// sized to fit the center region
jfrm.add(pp);

// Display the frame


jfrm.setVisible(true);
}

public static void main(String args[]) {


// Create the frame on the event dispatching thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new PaintDemo();
}
});
}
}

o/p
ImageButtonExample

package Swings;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ImageButtonExample {
JLabel l1;
ImageButtonExample (){
JFrame f=new JFrame("Image Button Example");

l1=new JLabel();
l1.setBounds(50,50, 700,100);
l1.setFont(new Font("Lucida Calligraphy",Font.BOLD,20));

JButton b=new JButton(new ImageIcon("//home//badhusha//Desktop//t2//digital.png"));


b.setBounds(150,150,100,100);
JButton b1=new JButton(new ImageIcon("//home//badhusha//Desktop//t2//hourglass.jpeg"));
b1.setBounds(500,150,100, 100);

b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
l1.setText("You have pressed digital clock!");
}
});

b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
l1.setText("You have pressed hour glass!");
}
});
f.add(b);
f.add(l1);
f.setSize(300,400);
f.add(b1);
f.add(l1);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ImageButtonExample();
}
}
JList Example

package Swings;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class JListExample extends JFrame {


private JList<String> countryList;
public JListExample() {
//create the model and add elements
DefaultListModel<String> listModel = new DefaultListModel<>();
listModel.addElement("USA");
listModel.addElement("India");
listModel.addElement("Vietnam");
listModel.addElement("Canada");
listModel.addElement("Denmark");
listModel.addElement("France");
listModel.addElement("Great Britain");
listModel.addElement("Japan");
listModel.addElement("Africa");
listModel.addElement("Greenland");
listModel.addElement("Singapore");
listModel.addElement("");
//create the list
countryList = new JList<>(listModel);
countryList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
final List<String> selectedValuesList = countryList.getSelectedValuesList();
System.out.println(selectedValuesList);
}
}
});
add(new JScrollPane(countryList));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("JList Example");
this.setSize(200, 200);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
new JListExample();
}
}

Login Form

package Swings;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class login {

public static void main(String[] args) {


// Creating instance of JFrame
JFrame frame = new JFrame("My First Swing Example");
// Setting the width and height of frame
frame.setSize(350, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

/* Creating panel. This is same as a div tag in HTML


* We can create several panels and add them to specific
* positions in a JFrame. Inside panels we can add text
* fields, buttons and other components.
*/
JPanel panel = new JPanel();
// adding panel to frame
frame.add(panel);

/* calling user defined method for adding components


* to the panel.
*/
placeComponents(panel);

// Setting the frame visibility to true


frame.setVisible(true);
}

private static void placeComponents(JPanel panel) {

/* We will discuss about layouts in the later sections


* of this tutorial. For now we are setting the layout
* to null
*/
panel.setLayout(null);

// Creating JLabel
JLabel userLabel = new JLabel("User");
JLabel jl= new JLabel();
jl.setBounds(30,130,400,40);
jl.setFont(new Font("Arial", Font.BOLD, 24));

/* This method specifies the location and size


* of component. setBounds(x, y, width, height)
* here (x,y) are coordinates from the top left
* corner and remaining two arguments are the width
* and height of the component.
*/
userLabel.setBounds(10,20,80,25);
panel.add(userLabel);

/* Creating text field where user is supposed to


* enter user name.
*/
JTextField userText = new JTextField(20);
userText.setBounds(100,20,165,25);
panel.add(userText);

// Same process for password label and text field.


JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10,50,80,25);
panel.add(passwordLabel);

/*This is similar to text field but it hides the user


* entered data and displays dots instead to protect
* the password like we normally see on login screens.
*/
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(100,50,165,25);
panel.add(passwordText);

// Creating login button


JButton loginButton = new JButton("login");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);
panel.add(jl);
loginButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
jl.setText("you have successfully logged in!");
}
});
}

}
Tabbed Pane Example

package Swings;
import java.awt.Color;

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

JPanel p1=new JPanel();

JPanel p2=new JPanel();


JPanel p3=new JPanel();
p1.setBackground(Color.BLUE);
p2.setBackground(Color.RED);
p3.setBackground(Color.GREEN);
JTabbedPane tp=new JTabbedPane();
tp.setBounds(50,50,200,200);
tp.add("BLUE",p1);
tp.add("RED",p2);
tp.add("GREEN",p3);
f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new TabbedPaneExample();
}}
SimpleAnimation

package Swings;
import javax.swing.*;

import java.awt.*;

final public class SimpleAnimation {


private JFrame frame;
private DrawPanel drawPanel;
private int oneX = 7;
private int oneY = 7;
private boolean up = false;
private boolean down = true;
private boolean left = false;
private boolean right = true;
private volatile boolean running = true;

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> new SimpleAnimation().go());
}

private void go() {


frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawPanel = new DrawPanel();
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setSize(300, 300);
frame.setLocation(375, 55);
frame.setResizable(true);
frame.setVisible(true);
// Start animation in a separate thread
Thread animationThread = new Thread(this::moveIt);
animationThread.start();
}

class DrawPanel extends JPanel {


@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

Graphics g1=getGraphics();
g.setColor(Color.blue);
g.fillOval(oneX, oneY,20,20);
//g.fillRect(oneX, oneY, 6, 6);
}
}

private void moveIt() {


while(running) {
if(oneX >= 283) {
right = false;
left = true;
}
if(oneX <= 7) {
right = true;
left = false;
}
if(oneY >= 265) {
up = true;
down = false;
}
if(oneY <= 7) {
up = false;
down = true;
}
if(up) oneY--;
if(down) oneY++;
if(left) oneX--;
if(right) oneX++;

try {
Thread.sleep(10);
SwingUtilities.invokeLater(() -> frame.repaint());
} catch (InterruptedException exc) {
Thread.currentThread().interrupt();
break;
}
}
}
}

Mouse Listener Example

package Swings;
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample2 extends Frame implements MouseListener
{
Label l;
MouseListenerExample2(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,400,20);
l.setFont(new Font("Arial", Font.BOLD, 24));
add(l);
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) {
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 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();
}
}
Table Example

package Swings;
import java.awt.Color;
import java.awt.Font;

//Table example using swing


import javax.swing.*;
import javax.swing.plaf.FontUIResource;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
FontUIResource font = new FontUIResource("Arial", Font.BOLD,16);
UIManager.put("Table.font", font);
UIManager.put("Table.foreground", Color.BLUE);
String data[][]={ {"101","Amit","670000","12000","10000"},
{"102","Jai","780000","12000","10000"},
{"103","Sachin","700000","12000","10000"},
{"104","Amot","670000","12000","10000"},
{"105","Jaiganesh","780000","12000","10000"},
{"106","Sanjay","700000","12000","10000"}
};
String column[]={"ID","NAME","SALARY","BONUS","TRAVELLING ALLOWANCE"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,300,400);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
Factorial Calculation

package Swings;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class FactorialCalculator extends JFrame {


private JTextField inputField;
private JTextField resultField;
private JButton computeButton;

public FactorialCalculator() {
// Set up the frame
setTitle("Factorial Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();

// Create components
JLabel inputLabel = new JLabel("Enter a number: ");
inputField = new JTextField(10);
JLabel resultLabel = new JLabel("Factorial: ");
resultField = new JTextField(15);
resultField.setEditable(false);
computeButton = new JButton("Compute");

// Add components with GridBagLayout


gbc.insets = new Insets(5, 5, 5, 5);

gbc.gridx = 0;
gbc.gridy = 0;
add(inputLabel, gbc);

gbc.gridx = 1;
gbc.gridy = 0;
add(inputField, gbc);

gbc.gridx = 0;
gbc.gridy = 1;
add(resultLabel, gbc);

gbc.gridx = 1;
gbc.gridy = 1;
add(resultField, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(computeButton, gbc);

// Add action listener to the button


computeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int number = Integer.parseInt(inputField.getText());
if (number < 0) {
JOptionPane.showMessageDialog(null,
"Please enter a non-negative number",
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
long result = calculateFactorial(number);
resultField.setText(String.valueOf(result));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null,
"Please enter a valid integer",
"Error",
JOptionPane.ERROR_MESSAGE);
} catch (ArithmeticException ex) {
JOptionPane.showMessageDialog(null,
"Number too large to calculate factorial",
"Error",
JOptionPane.ERROR_MESSAGE);
}
}
});

// Pack and display


pack();
setLocationRelativeTo(null);
}

private long calculateFactorial(int n) {


if (n > 20) {
throw new ArithmeticException("Number too large");
}
if (n == 0 || n == 1) {
return 1;
}
long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FactorialCalculator().setVisible(true);
}
});
}
}

Text Case Convertor

package Swings;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TextCaseConvertor extends JFrame {


private JTextField inputField;
private JTextField upperCaseField;
private JTextField lowerCaseField;
private JTextField reverseField;
private JTextField lengthField;
private JButton processButton;

public TextCaseConvertor() {
// Set up the frame
setTitle("String Manipulator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();

// Create components
JLabel inputLabel = new JLabel("Enter a string: ");
inputField = new JTextField(20);

JLabel upperCaseLabel = new JLabel("Uppercase: ");


upperCaseField = new JTextField(20);
upperCaseField.setEditable(false);

JLabel lowerCaseLabel = new JLabel("Lowercase: ");


lowerCaseField = new JTextField(20);
lowerCaseField.setEditable(false);

JLabel reverseLabel = new JLabel("Reverse: ");


reverseField = new JTextField(20);
reverseField.setEditable(false);

JLabel lengthLabel = new JLabel("Length: ");


lengthField = new JTextField(20);
lengthField.setEditable(false);

processButton = new JButton("Process String");

// Layout components using GridBagLayout


gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;

// Input row
gbc.gridx = 0;
gbc.gridy = 0;
add(inputLabel, gbc);

gbc.gridx = 1;
add(inputField, gbc);

// Uppercase row
gbc.gridx = 0;
gbc.gridy = 1;
add(upperCaseLabel, gbc);

gbc.gridx = 1;
add(upperCaseField, gbc);

// Lowercase row
gbc.gridx = 0;
gbc.gridy = 2;
add(lowerCaseLabel, gbc);

gbc.gridx = 1;
add(lowerCaseField, gbc);

// Reverse row
gbc.gridx = 0;
gbc.gridy = 3;
add(reverseLabel, gbc);

gbc.gridx = 1;
add(reverseField, gbc);

// Length row
gbc.gridx = 0;
gbc.gridy = 4;
add(lengthLabel, gbc);

gbc.gridx = 1;
add(lengthField, gbc);

// Button row
gbc.gridx = 0;
gbc.gridy = 5;
gbc.gridwidth = 2;
add(processButton, gbc);

// Add action listener to the button


processButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
processString();
}
});

// Add key listener to input field


inputField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
processString();
}
}
});

// Pack and display


pack();
setLocationRelativeTo(null);
}
private void processString() {
String input = inputField.getText();

// Process the string


upperCaseField.setText(input.toUpperCase());
lowerCaseField.setText(input.toLowerCase());
reverseField.setText(new StringBuilder(input).reverse().toString());
lengthField.setText(String.valueOf(input.length()));
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TextCaseConvertor().setVisible(true);
}
});
}
}

Palindrome Number Checker

package Swings;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class NumberPalindromeChecker extends JFrame {


private JTextField inputField;
private JTextField reverseField;
private JTextField statusField;
private JButton checkButton;

public NumberPalindromeChecker() {
// Set up the frame
setTitle("Number Palindrome Checker");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();

// Create components
JLabel inputLabel = new JLabel("Enter a number: ");
inputField = new JTextField(15);

JLabel reverseLabel = new JLabel("Reverse: ");


reverseField = new JTextField(15);
reverseField.setEditable(false);

JLabel statusLabel = new JLabel("Status: ");


statusField = new JTextField(15);
statusField.setEditable(false);

checkButton = new JButton("Check Palindrome");

// Layout components using GridBagLayout


gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;

// Input row
gbc.gridx = 0;
gbc.gridy = 0;
add(inputLabel, gbc);

gbc.gridx = 1;
add(inputField, gbc);

// Reverse row
gbc.gridx = 0;
gbc.gridy = 1;
add(reverseLabel, gbc);

gbc.gridx = 1;
add(reverseField, gbc);

// Status row
gbc.gridx = 0;
gbc.gridy = 2;
add(statusLabel, gbc);

gbc.gridx = 1;
statusField.setBackground(new Color(240, 240, 240));
add(statusField, gbc);

// Button row
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 2;
add(checkButton, gbc);

// Add action listener to the button


checkButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
checkPalindrome();
}
});

// Add key listener to input field


inputField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
checkPalindrome();
}
}
});

// Pack and display


pack();
setLocationRelativeTo(null);
}

private void checkPalindrome() {


try {
String input = inputField.getText().trim();
if (input.isEmpty()) {
JOptionPane.showMessageDialog(this,
"Please enter a number",
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}

long number = Long.parseLong(input);


String reversed = new StringBuilder(String.valueOf(number)).reverse().toString();
reverseField.setText(reversed);

boolean isPalindrome = input.equals(reversed);


if (isPalindrome) {
statusField.setText("It's a Palindrome!");
statusField.setForeground(new Color(0, 128, 0)); // Green color
} else {
statusField.setText("Not a Palindrome");
statusField.setForeground(new Color(178, 34, 34)); // Red color
}

} catch (NumberFormatException ex) {


JOptionPane.showMessageDialog(this,
"Please enter a valid number",
"Error",
JOptionPane.ERROR_MESSAGE);
inputField.setText("");
reverseField.setText("");
statusField.setText("");
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new NumberPalindromeChecker().setVisible(true);
}
});
}
}

ToggleButton

This application creates a simple light switch simulator using a JToggleButton. Here's what the code
does:
1. Creates a window with a toggle button, a status label, and a panel representing a light
2. When the toggle button is clicked:
 The status label updates to show whether the light is ON or OFF
 The light panel changes color (gray when off, yellow when on)
3. Uses proper layout management with BoxLayout and spacing
4. Follows Swing best practices like running on the Event Dispatch Thread
To run this application:
1. Copy the code into a file named ToggleButtonDemo.java
2. Compile it: javac ToggleButtonDemo.java
3. Run it: java ToggleButtonDemo

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ToggleButtonDemo extends JFrame {


private JToggleButton toggleButton;
private JLabel statusLabel;
private JPanel lightPanel;

public ToggleButtonDemo() {
// Set up the frame
setTitle("Toggle Button Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout(10, 10));
setSize(300, 200);

// Create main panel with padding


JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

// Create toggle button


toggleButton = new JToggleButton("Light Switch");
toggleButton.setAlignmentX(Component.CENTER_ALIGNMENT);

// Create status label


statusLabel = new JLabel("Light is OFF");
statusLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

// Create light panel


lightPanel = new JPanel();
lightPanel.setPreferredSize(new Dimension(100, 100));
lightPanel.setBackground(Color.GRAY);
lightPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));

// Add action listener to toggle button


toggleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (toggleButton.isSelected()) {
statusLabel.setText("Light is ON");
lightPanel.setBackground(Color.YELLOW);
} else {
statusLabel.setText("Light is OFF");
lightPanel.setBackground(Color.GRAY);
}
}
});

// Add components to main panel


mainPanel.add(toggleButton);
mainPanel.add(Box.createRigidArea(new Dimension(0, 10)));
mainPanel.add(statusLabel);
mainPanel.add(Box.createRigidArea(new Dimension(0, 10)));
mainPanel.add(lightPanel);

// Add main panel to frame


add(mainPanel);

// Center the frame on screen


setLocationRelativeTo(null);
}

public static void main(String[] args) {


// Run the application on the Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ToggleButtonDemo().setVisible(true);
}
});
}
}

o/p
Check Boxes

atures. Here's what the application does:


1. Displays a list of pizza toppings as checkboxes with their prices
2. Updates the total price automatically when checkboxes are selected/deselected
3. Includes a reset button to clear all selections
4. Uses proper layout management and spacing
5. Follows Swing best practices
Key features demonstrated:
 Creating and styling checkboxes
 Handling checkbox events
 Maintaining a running total
 Resetting multiple checkboxes
 Proper UI organization with panels and layouts
 Price formatting
To run the application:
1. Save the code as CheckboxDemo.java
2. Compile it: javac CheckboxDemo.java
3. Run it: java CheckboxDemo

Would you like me to add any additional features or modify the existing functionality? For example, I
could:
 Add a submit order button
 Include a quantity selector for each topping
 Add more styling options
 Include a base pizza price
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CheckboxDemo extends JFrame {


private JPanel toppingsPanel;
private JLabel totalLabel;
private double totalPrice = 0.0;

// Checkbox prices
private final double CHEESE_PRICE = 1.50;
private final double PEPPERONI_PRICE = 2.00;
private final double MUSHROOM_PRICE = 1.75;
private final double OLIVES_PRICE = 1.25;
public CheckboxDemo() {
// Set up the frame
setTitle("Pizza Toppings Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout(10, 10));
setSize(400, 300);

// Create main panel with padding


JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

// Create title label


JLabel titleLabel = new JLabel("Select Your Pizza Toppings");
titleLabel.setFont(new Font("Arial", Font.BOLD, 16));
titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

// Create toppings panel


toppingsPanel = new JPanel();
toppingsPanel.setLayout(new BoxLayout(toppingsPanel, BoxLayout.Y_AXIS));
toppingsPanel.setBorder(BorderFactory.createTitledBorder("Available Toppings"));

// Create checkboxes with prices


JCheckBox cheeseBox = createTopping("Extra Cheese", CHEESE_PRICE);
JCheckBox pepperoniBox = createTopping("Pepperoni", PEPPERONI_PRICE);
JCheckBox mushroomBox = createTopping("Mushrooms", MUSHROOM_PRICE);
JCheckBox olivesBox = createTopping("Olives", OLIVES_PRICE);

// Add checkboxes to toppings panel


toppingsPanel.add(cheeseBox);
toppingsPanel.add(Box.createRigidArea(new Dimension(0, 5)));
toppingsPanel.add(pepperoniBox);
toppingsPanel.add(Box.createRigidArea(new Dimension(0, 5)));
toppingsPanel.add(mushroomBox);
toppingsPanel.add(Box.createRigidArea(new Dimension(0, 5)));
toppingsPanel.add(olivesBox);

// Create total price label


totalLabel = new JLabel("Total Price: $0.00");
totalLabel.setFont(new Font("Arial", Font.BOLD, 14));
totalLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

// Create reset button


JButton resetButton = new JButton("Reset Selection");
resetButton.setAlignmentX(Component.CENTER_ALIGNMENT);
resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
resetSelections();
}
});

// Add components to main panel


mainPanel.add(titleLabel);
mainPanel.add(Box.createRigidArea(new Dimension(0, 20)));
mainPanel.add(toppingsPanel);
mainPanel.add(Box.createRigidArea(new Dimension(0, 20)));
mainPanel.add(totalLabel);
mainPanel.add(Box.createRigidArea(new Dimension(0, 10)));
mainPanel.add(resetButton);

// Add main panel to frame


add(mainPanel);

// Center the frame on screen


setLocationRelativeTo(null);
}

private JCheckBox createTopping(String name, double price) {


JCheckBox checkbox = new JCheckBox(String.format("%s ($%.2f)", name, price));
checkbox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateTotal();
}
});
return checkbox;
}

private void updateTotal() {


totalPrice = 0.0;
Component[] components = toppingsPanel.getComponents();

for (Component component : components) {


if (component instanceof JCheckBox) {
JCheckBox checkbox = (JCheckBox) component;
if (checkbox.isSelected()) {
if (checkbox.getText().contains("Cheese")) totalPrice += CHEESE_PRICE;
if (checkbox.getText().contains("Pepperoni")) totalPrice += PEPPERONI_PRICE;
if (checkbox.getText().contains("Mushrooms")) totalPrice += MUSHROOM_PRICE;
if (checkbox.getText().contains("Olives")) totalPrice += OLIVES_PRICE;
}
}
}

totalLabel.setText(String.format("Total Price: $%.2f", totalPrice));


}
private void resetSelections() {
Component[] components = toppingsPanel.getComponents();
for (Component component : components) {
if (component instanceof JCheckBox) {
((JCheckBox) component).setSelected(false);
}
}
updateTotal();
}

public static void main(String[] args) {


// Run the application on the Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new CheckboxDemo().setVisible(true);
}
});
}
}
o/p

Radio Buttons

Here's what the application does:


1. Allows selection of pizza size using radio buttons (only one size can be selected)
2. Allows selection of crust type using radio buttons (only one type can be selected)
3. Shows the current selection and updates the total price automatically
4. Includes a place order button with confirmation dialog
5. Uses proper layout management and spacing
6. Groups related radio buttons using ButtonGroup
Key features demonstrated:
 Creating and grouping radio buttons
 Handling radio button events
 Maintaining selections across button groups
 Price calculations based on selections
 Dialog boxes for user feedback
 Proper UI organization with panels and layouts
To run the application:
1. Save the code as RadioButtonDemo.java
2. Compile it: javac RadioButtonDemo.java
3. Run it: java RadioButtonDemo

Would you like me to add any additional features or modify the existing functionality? For example, I
could:
 Add more customization options
 Include a delivery/pickup option
 Add a quantity selector
 Include special instructions input

package Swings;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Enumeration;

class RadioButtonDemo extends JFrame {


private JLabel selectionLabel;
private ButtonGroup sizeGroup;

public RadioButtonDemo() {
setTitle("Pizza Size Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);

// Create main panel


JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

// Create title
JLabel titleLabel = new JLabel("Select Pizza Size");
titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
mainPanel.add(titleLabel);
mainPanel.add(Box.createVerticalStrut(20));

// Create radio button panel


JPanel radioPanel = new JPanel();
radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));
radioPanel.setBorder(BorderFactory.createEtchedBorder());

// Create button group


sizeGroup = new ButtonGroup();

// Create radio buttons


String[] sizes = {"Small - $8.99", "Medium - $10.99", "Large - $12.99", "Extra Large - $14.99"};
for (String size : sizes) {
JRadioButton rb = new JRadioButton(size);
rb.setAlignmentX(Component.LEFT_ALIGNMENT);
rb.addActionListener(e -> updateSelection());
sizeGroup.add(rb);
radioPanel.add(rb);
radioPanel.add(Box.createVerticalStrut(5));
}

mainPanel.add(radioPanel);
mainPanel.add(Box.createVerticalStrut(20));

// Create selection label


selectionLabel = new JLabel("Your selection: None");
selectionLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
mainPanel.add(selectionLabel);

// Add order button


JButton orderButton = new JButton("Place Order");
orderButton.setAlignmentX(Component.CENTER_ALIGNMENT);
orderButton.addActionListener(e -> {
if (getSelectedSize() != null) {
JOptionPane.showMessageDialog(this,
"Order placed: " + getSelectedSize(),
"Order Confirmation",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this,
"Please select a size first!",
"Selection Required",
JOptionPane.WARNING_MESSAGE);
}
});

mainPanel.add(Box.createVerticalStrut(20));
mainPanel.add(orderButton);

// Add main panel to frame


add(mainPanel);
}

private String getSelectedSize() {


for (Enumeration<AbstractButton> buttons = sizeGroup.getElements();
buttons.hasMoreElements();) {
AbstractButton button = buttons.nextElement();
if (button.isSelected()) {
return button.getText();
}
}
return null;
}

private void updateSelection() {


String selected = getSelectedSize();
if (selected != null) {
selectionLabel.setText("Your selection: " + selected);
} else {
selectionLabel.setText("Your selection: None");
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
RadioButtonDemo frame = new RadioButtonDemo();
frame.setVisible(true);
});
}
}
o/p

You might also like