爲單選框添加事件 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);


 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章