Radio Button Example : Java Swing

A very interesting example of swing radio button. Here we are using 3 radio buttons. If user select any radio button, a message box will display. The source code is here :


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

public class SelectRadioButton{
JLabel label;
public static void main(String[] args){
SelectRadioButton sr = new SelectRadioButton();
}

public SelectRadioButton(){
JFrame frame = new JFrame("Button Selection Example");
JRadioButton first = new JRadioButton("Button1");
JRadioButton second = new JRadioButton("Button2");
JRadioButton third = new JRadioButton("Button3");
JPanel panel = new JPanel();
panel.add(first);
panel.add(second);
panel.add(third);
panel.add(fourth);
panel.add(fifth);
ButtonGroup bg = new ButtonGroup();
bg.add(first);
bg.add(second);
bg.add(third);
bg.add(fourth);
bg.add(fifth);
first.addActionListener(new MyAction());
second.addActionListener(new MyAction());
third.addActionListener(new MyAction());
fourth.addActionListener(new MyAction());
fifth.addActionListener(new MyAction());
label = new JLabel("Java Swing Example");
frame.add(panel, BorderLayout.NORTH);
frame.add(label, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public class MyAction implements ActionListener{
public void actionPerformed(ActionEvent e){
label.setText(e.getActionCommand());
JOptionPane.showMessageDialog(null,"You have selected : " + e.getActionCommand() +
" radio button.");
}
}
}


1 comments:

maya said...

All over presentation is really very good. Keep it up your good job....