Wednesday, November 29, 2006

JRadioButton: Simpler Example



import javax.swing.*;
import java.awt.*;
import java.awt.event.*; // step 1

// Mututally exclusive == >ButtonGroup

public class JRadioButtonDemo extends JFrame //step 2
implements ActionListener{

private JRadioButton rbtn1 = new JRadioButton("Ivan");
private JRadioButton rbtn2 = new JRadioButton("Kwan Yong");
private JButton btn = new JButton("Vote");

private ButtonGroup btngrp = new ButtonGroup();

public JRadioButtonDemo() {

btngrp.add(rbtn1); // For making one radiobutton clickable at one time
btngrp.add(rbtn2);

rbtn1.setSelected(true); // Set Ivan to be default

getContentPane().setLayout(new FlowLayout());
getContentPane().add(rbtn1);
getContentPane().add(rbtn2);
getContentPane().add(btn);

btn.addActionListener(this);//step 4:

} //end constructor

public void actionPerformed(ActionEvent ev){//step 3

String name = "";
if (ev.getSource() == btn){
if (rbtn1.isSelected()){ // Ivan was voted
name = "Ivan";
}
else if (rbtn2.isSelected()){
name = "Kwan Yong";
}

JOptionPane.showMessageDialog(null, "You voted for " + name);
}//end if

} //end actionPerformed

public static void main(String[] args) {
JRadioButtonDemo f = new JRadioButtonDemo();
f.setTitle("OOPG");
f.setSize(300, 300);
f.setVisible(true);

} //end main
} //end class

No comments: