0% found this document useful (0 votes)
4 views56 pages

MODULE 3 - Java Swing Tutorial

The document provides a comprehensive tutorial on Java Swing, a part of Java Foundation Classes (JFC) used for creating window-based applications. It highlights the differences between AWT and Swing, explains the Model-View-Controller (MVC) architecture, and details various Swing components and their functionalities. Additionally, it includes examples of creating GUI elements such as JFrame, JButton, and layout managers like BorderLayout.

Uploaded by

1by23is151
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)
4 views56 pages

MODULE 3 - Java Swing Tutorial

The document provides a comprehensive tutorial on Java Swing, a part of Java Foundation Classes (JFC) used for creating window-based applications. It highlights the differences between AWT and Swing, explains the Model-View-Controller (MVC) architecture, and details various Swing components and their functionalities. Additionally, it includes examples of creating GUI elements such as JFrame, JButton, and layout managers like BorderLayout.

Uploaded by

1by23is151
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/ 56

Java Swing tutorial is a part of Java

Foundation Classes (JFC) that is used to create


window-based applications. It is built on the top
of AWT (Abstract Windowing Toolkit) API and
entirely written in java.
Unlike AWT, Java Swing provides platform-
independent and lightweight components.
The javax.swing package provides classes for
java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
Difference between AWT and Swing

No. Java AWT Java Swing

1) AWT components Java swing


are platform- components
dependent. are platform-
independent.
2) AWT components Swing components
are heavyweight. are lightweight.
3) AWT doesn't support Swing supports
pluggable look and pluggable look and
feel. feel.
4) AWT provides less Swing provides more
components than powerful
Swing. components such as
tables, lists,
scrollpanes,
colorchooser,
tabbedpane etc.
5) AWT doesn't follows Swing follows MVC.
MVC(Model View
Controller) where
model represents data,
view represents
presentation and
controller acts as an
interface between
model and view.
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
Model view controller
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.
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.

Components and Containers


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
What is JFC
The Java Foundation Classes (JFC) are a set of
GUI components which simplify the
development of desktop applications.
The hierarchy of Swing API
The following table shows the class names for
Swing components (including those used as
containers).
Commonly used Methods of Component class
The methods of Component class are widely
used in java swing that are given below.

Method Description

public void add(Component add a


c) component on
another
component.
public void setSize(int sets size of the
width,int height) component.
public void sets the layout
setLayout(LayoutManager manager for the
m) component.
public void sets the visibility
setVisible(boolean b) of the
component. It is
by default fals

Two ways to create JFrame


o By creating the object of Frame class
(association)
o By extending Frame class (inheritance)

import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JF
rame
JButton b=new JButton("click");//creating instan
ce of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, wid
th, 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
}
}

Example of Swing by Association inside


constructor
We can also write all the codes of creating
JFrame, JButton and method call inside the java
constructor.
import javax.swing.*;
public class Simple {
JFrame f;
Simple(){
f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instan


ce of JButton
b.setBounds(130,100,100, 40);

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height


f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}

public static void main(String[] args) {


new Simple();
}

Top level Containers


1. JFrame

2. JDialogBox

General purpose Containers


1. JPanel
2. JScrollPane
3. JTabbedPane
4. JSplitPane
Components in Swing
1. JFrame: JFrame is a top-level container
that represents the main window of a GUI
application. It provides a title bar, and
minimizes, maximizes, and closes buttons.
JFrame fr = new JFrame(“My frame”);
2. JPanel: JPanel is a container that can
hold other components. It is commonly used
to group related components together.
JPanel jp = new JPanel();
3. JButton: JButton is a component that
represents a clickable button. It is commonly
used to trigger actions in a GUI application.
JButton bt= new JButton(“yes”);
Example
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
Java JButton Example with ActionListener
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
});
f.add(b);
f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
4. JLabel: JLabel is a component that
displays text or an image. It is commonly used
to provide information or to label other
components.
JLabel lable = new JLabel(“user Name”);
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}

5. JTextField: JTextField is a component


that allows the user to input text. It is
commonly used to get input from the user,
such as a name or an address.
JTextField tf = new JTextField();
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example
");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoin
t.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
6. JCheckBox: JCheckBox is a component
that represents a checkbox. It is commonly
used to get a binary input from the user, such
as whether or not to enable a feature.

JCheckBox jc = new JCheckBox(“Java”);


import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Exa
mple");
JCheckBox checkBox1 = new JCheckBo
x("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBo
x("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}

 public static void main(String args[])


 {
 new CheckBoxExample();
 }}

7. JList: JList is a component that


represents a list of elements. It is typically
used to display a list of options from which the
user can select one or more items.
import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new De
faultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}}
8. JTable: JTable is a component that
represents a data table. It is typically used to
present data in a tabular fashion, such as a
list of products or a list of orders.
import javax.swing.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},

{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};

JTable jt=new JTable(data,column);


jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}

9. JScrollPane: JScrollPane is a component


that provides scrolling functionality to other
components. It is commonly used to add
scrolling to a panel or a table.
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;

public class JScrollPaneExample {


private static final long serialVersionUID
= 1L;

private static void createAndShowGUI() {

// Create and set up the window.


final JFrame frame = new JFrame("Scro
ll Pane Example");

// Display the window.


frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame
.EXIT_ON_CLOSE);
// set flow layout for the frame
frame.getContentPane().setLayout(new
FlowLayout());

JTextArea textArea = new JTextArea(20,


20);
JScrollPane scrollableTextArea = new J
ScrollPane(textArea);

scrollableTextArea.setHorizontalScrollB
arPolicy(JScrollPane.HORIZONTAL_SCROLLB
AR_ALWAYS);
scrollableTextArea.setVerticalScrollBarP
olicy(JScrollPane.VERTICAL_SCROLLBAR_AL
WAYS);

frame.getContentPane().add(scrollableT
extArea);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(n
ew Runnable() {

public void run() {


createAndShowGUI();
}
});
}
}

Java LayoutManagers
The LayoutManagers are used to arrange
components in a particular manner. The Java
LayoutManagers facilitates us to control the
positioning and size of the components in GUI
forms. LayoutManager is an interface that is
implemented by all the classes of layout
managers. There are the following classes that
represent the layout managers:
1. java.awt.BorderLayout
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.
Java BorderLayout
The BorderLayout is used to arrange the
components in five regions: north, south, east,
west, and center. Each region (area) may
contain one component only. It is the default
layout of a frame or window. The BorderLayout
provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors
BorderLayout(): creates a border layout but
with no gaps between the components.
BorderLayout(int hgap, int vgap): creates a
border layout with the given horizontal and
vertical gaps between the components.
import java.awt.*;
import javax.swing.*;

public class Border


{
JFrame f;
Border()
{
f = new JFrame();

// creating buttons
JButton b1 = new JButton("NORTH");; // the
button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the b
utton will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the but
ton will be labeled as EAST
JButton b4 = new JButton("WEST");; // the bu
tton will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the
button will be labeled as CENTER

f.add(b1, BorderLayout.NORTH); // b1 will be


placed in the North Direction
f.add(b2, BorderLayout.SOUTH); // b2 will be
placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be pl
aced in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be pl
aced in the West Direction
f.add(b5, BorderLayout.CENTER); // b2 will be
placed in the Center

f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}

Example of BorderLayout class: Using


BorderLayout(int hgap, int vgap) constructor
The following example inserts horizontal and
vertical gaps between buttons using the
parameterized constructor BorderLayout(int
hgap, int gap)
FileName: BorderLayoutExample.java

// import statement
import java.awt.*;
import javax.swing.*;
public class BorderLayoutExample
{
JFrame jframe;
// constructor
BorderLayoutExample()
{
// creating a Frame
jframe = new JFrame();
// create buttons
JButton btn1 = new JButton("NORTH");
JButton btn2 = new JButton("SOUTH");
JButton btn3 = new JButton("EAST");
JButton btn4 = new JButton("WEST");
JButton btn5 = new JButton("CENTER");
// creating an object of the BorderLayout cla
ss using
// the parameterized constructor where the h
orizontal gap is 20
// and vertical gap is 15. The gap will be evid
ent when buttons are placed
// in the frame
jframe.setLayout(new BorderLayout(20, 15));
jframe.add(btn1, BorderLayout.NORTH);
jframe.add(btn2, BorderLayout.SOUTH);
jframe.add(btn3, BorderLayout.EAST);
jframe.add(btn4, BorderLayout.WEST);
jframe.add(btn5, BorderLayout.CENTER);
jframe.setSize(300,300);
jframe.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new BorderLayoutExample();
}
}

ava FlowLayout
The Java FlowLayout class is used to arrange
the components in a line, one after another (in
a flow). It is the default layout of the applet or
panel.
Fields of FlowLayout class
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Constructors of FlowLayout class
1. FlowLayout(): creates a flow layout with
centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow
layout with the given alignment and a
default 5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int
vgap): creates a flow layout with the given
alignment and the given horizontal and
vertical gap.
Example of FlowLayout class: Using
FlowLayout() constructor
FileName: FlowLayoutExample.java
// import statements
import java.awt.*;
import javax.swing.*;

public class FlowLayoutExample


{

JFrame frameObj;

// constructor
FlowLayoutExample()
{
// creating a frame object
frameObj = new JFrame();

// creating the buttons


JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("10");
// adding the buttons to frame
frameObj.add(b1); frameObj.add(b2); frameO
bj.add(b3); frameObj.add(b4);
frameObj.add(b5); frameObj.add(b6); frameO
bj.add(b7); frameObj.add(b8);
frameObj.add(b9); frameObj.add(b10);

// parameter less constructor is used


// therefore, alignment is center
// horizontal as well as the vertical gap is 5 un
its.
frameObj.setLayout(new FlowLayout());

frameObj.setSize(300, 300);
frameObj.setVisible(true);
}

// main method
public static void main(String argvs[])
{
new FlowLayoutExample();
}
}
Example of FlowLayout class: Using
FlowLayout(int align, int hgap, int vgap)
constructor
FileName: FlowLayoutExample1.java
// import statement
import java.awt.*;
import javax.swing.*;

public class FlowLayoutExample1


{
JFrame frameObj;
// constructor
FlowLayoutExample1()
{
// creating a frame object
frameObj = new JFrame();

// creating the buttons


JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("10");

// adding the buttons to frame


frameObj.add(b1); frameObj.add(b2); frameO
bj.add(b3); frameObj.add(b4);
frameObj.add(b5); frameObj.add(b6); frameO
bj.add(b7); frameObj.add(b8);
frameObj.add(b9); frameObj.add(b10);

// parameterized constructor is used


// where alignment is left
// horizontal gap is 20 units and vertical gap i
s 25 units.
frameObj.setLayout(new FlowLayout(FlowLay
out.LEFT, 20, 25));

frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new FlowLayoutExample1();
}
}
Output:
Event and Listener (Java Event Handling)
Changing the state of an object is known as an
event. For example, click on button, dragging
mouse etc. The java.awt.event package provides
many event classes and Listener interfaces for
event handling.
Java Event classes and Listener interfaces

vent Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and


MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener
ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling


Following steps are required to perform event
handling:
1. Register the component with the Listener
Registration Methods
For registering the component with the
Listener, many classes provide the registration
methods. For example:
o Button
o public void
addActionListener(ActionListener a){}
o MenuItem
o public void
addActionListener(ActionListener a){}
o TextField
o public void
addActionListener(ActionListener a){}
o public void
addTextListener(TextListener a){}
o TextArea
o public void
addTextListener(TextListener a){}
o Checkbox
o public void
addItemListener(ItemListener a){}
o Choice
o public void
addItemListener(ItemListener a){}
o List
o public void
addActionListener(ActionListener a){}
o public void
addItemListener(ItemListener a){}
Java Event Handling Code
We can put the event handling code into one
of the following places:
1. Within class
2. Other class
3. Anonymous class
Java event handling by implementing
ActionListener
Java event handling by implementing
ActionListener
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements Actio
nListener{
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 insta
nce

//add components and set size, layout and visibi


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

2) Java event handling by outer class


import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame{
TextField tf;
AEvent2(){
//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
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class inst
ance
//add components and set size, layout and visibi
lity
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
}
import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}

3) Java event handling by anonymous class


import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame{
TextField tf;
AEvent3(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);

b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}
Java Adapter Classes
Java adapter classes provide the default implementation of
listener interfaces. If you inherit the adapter class, you will
not be forced to provide the implementation of all the
methods of listener interfaces. So it saves code.

 Features of adopter classes


 It assists the unrelated classes to work combined.
 It provides ways to use classes in different ways.
 It increases the transparency of classes.
 It provides a way to include related patterns in the
class.
 It provides a pluggable kit for developing an
application.
 It increases the reusability of the class.’
java.awt. event Adapter classes

MouseAdapterExample.java

// importing the necessary libraries


import java.awt.*;
import java.awt.event.*;

// class which inherits the MouseAdapter class


public class MouseAdapterExample extends MouseAdapter {
// object of Frame class
Frame f;
// class constructor
MouseAdapterExample() {
// creating the frame with the title
f = new Frame ("Mouse Adapter");
// adding MouseListener to the Frame
f.addMouseListener(this);
// setting the size, layout and visibility of the frame
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true);
}
// overriding the mouseClicked() method of the MouseAdapter class
public void mouseClicked (MouseEvent e) {
// creating the Graphics object and fetching them from the Frame object using getGraph
ics() method
Graphics g = f.getGraphics();
// setting the color of graphics object
g.setColor (Color.BLUE);
// setting the shape of graphics object
g.fillOval (e.getX(), e.getY(), 30, 30);
}
// main method
public static void main(String[] args) {
new MouseAdapterExample();
}
}
Java JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on or
off.

import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JToggleButton;

public class JToggleButtonExample extends JFrame implements ItemListener {


public static void main(String[] args) {
new JToggleButtonExample();
}
private JToggleButton button;
JToggleButtonExample() {
setTitle("JToggleButton with ItemListener Example");
setLayout(new FlowLayout());
setJToggleButton();
setAction();
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void setJToggleButton() {
button = new JToggleButton("ON");
add(button);
}
private void setAction() {
button.addItemListener(this);
}
public void itemStateChanged(ItemEvent eve) {
if (button.isSelected())
button.setText("OFF");
else
button.setText("ON");
}
}

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.

import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}

Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option
from multiple options. It is widely used in exam systems or quiz.

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


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

You might also like