Home Tutorial Java Swing Java Swing: Validate radiobutton

 
 

Share on Google+Share on Google+
Java Swing: Validate radiobutton
Posted on: September 25, 2012 at 12:00 AM
Advertisement
In this tutorial, you will learn how to validate radiobuttons in Java Swing.

Java Swing: Validate radiobutton

In this tutorial, you will learn how to validate radiobuttons in Java Swing.

Radio buttons are the group of buttons where only one button can be selected at a time. Swing supports radio buttons with the classes JRadioButton and ButtonGroup classes. In swing, all the radio buttons have to be added to ButtonGroup to allow to select only one button at a time. In the given example, we have created two radiobuttons and check whether any of the button is clicked or not. If none button has been clicked, then an error message will be displayed using JOptionPane.showMessageDialog() method.

Example

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

public class RadioButtonValidation{
JTextField text;

public static void main(String[] args) throws Exception{
new RadioButtonValidation();
}

public RadioButtonValidation(){
JFrame f = new JFrame();
f.getContentPane().setLayout(null);
JLabel lab = new JLabel("Gender");
final JRadioButton Male,Female;
ButtonGroup radioGroup=new ButtonGroup();
Male=new JRadioButton("Male");
radioGroup.add(Male);
Female=new JRadioButton("Female");
radioGroup.add(Female);
JButton button=new JButton("Submit");
lab.setBounds(50,20,70,20);
Male.setBounds(110,20,100,20);
Female.setBounds(210,20,100,20);
button.setBounds(50,50,80,15);


button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if((Male.isSelected()==false)&&(Female.isSelected()==false)){
JOptionPane.showMessageDialog(null,"Please select radio button");
}
}
});
f.add(lab);
f.add(Male);
f.add(Female);
f.add(button);

f.setSize(350,120);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Output:

Onclicking without selecting any button, you will get message

Advertisement

Related Tags for Java Swing: Validate radiobutton:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 25, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com