import javax.swing.*;
import java.awt.*;
import java.awt.event.*; // step 1
// Mututally exclusive == >ButtonGroup
public class JRadioButtonDemo2 extends JFrame //step 2
implements ActionListener{
private JRadioButton rbtn1 = new JRadioButton("Ivan");
private JRadioButton rbtn2 = new JRadioButton("Kwan Yong");
private JTextArea ta1 = new JTextArea(5,30);
private JButton btn = new JButton("Vote");
private int ivan;
private int kwanyong;
private ButtonGroup btngrp = new ButtonGroup();
public JRadioButtonDemo2() {
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);
getContentPane().add(ta1); // textarea display the no.of votes
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";
ivan++;
}
else if (rbtn2.isSelected()){
name = "Kwan Yong";
kwanyong++;
}
JOptionPane.showMessageDialog(null, "You voted for " + name);
ta1.setText("Ivan:" + ivan + "\nKwan Yong:" + kwanyong);
}//end if
} //end actionPerformed
public static void main(String[] args) {
JRadioButtonDemo2 f = new JRadioButtonDemo2();
f.setTitle("OOPG");
f.setSize(300, 300);
f.setVisible(true);
} //end main
} //end class
Wednesday, November 29, 2006
JRadioButton: More Complicated Example
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment