1. 程式人生 > >為單選框新增事件 JRadioButton

為單選框新增事件 JRadioButton

 //RaidoButton.java
//為單選框新增事件
//2009-11-18
//<applet code=RadioButton width=200 height=100>
//</applet>

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


public class RadioButton extends JApplet
{


 JRadioButton radioButton1=new JRadioButton("RadioButton1");
 JRadioButton radioButton2=new JRadioButton("RadioButton2");
 ButtonGroup buttonGroup=new ButtonGroup();                                  //將兩者合為一組,否則沒有單選效果。
 JTextField txt=new JTextField(20);

 class ActionTry implements  ActionListener
 {
  public void  actionPerformed(ActionEvent e){
   if (e.getSource()==radioButton1)
   {
    txt.setText("radioButton1");
   }
   if (e.getSource()==radioButton2)
   {
    txt.setText("radioButton2");
   }
  }
 }

 ActionTry select=new ActionTry();

 public void init(){
  Container cp=getContentPane();
  cp.setLayout(new FlowLayout());

  cp.add(radioButton1);
  cp.add(radioButton2);
  cp.add(txt);
  
  radioButton1.addActionListener(select);
  radioButton2.addActionListener(select);
  buttonGroup.add(radioButton1);
  buttonGroup.add(radioButton2);


 }
}