响应RadioButton的事件是不是比较好呢?

解决方案 »

  1.   

    rb1.addActionListener(new ActionListener(){
       public void actionPerformed(ActionEvent e){
       System.out.println("rb1");
       }
      });  
    rb2.addActionListener(new ActionListener(){
       public void actionPerformed(ActionEvent e){
       System.out.println("rb2");
       }
       });
      

  2.   

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.sql.*;public class Application1 extends JFrame {
    JPanel contentPanel=(JPanel)this.getContentPane();
    JPanel jp=new JPanel(new GridLayout(4,1));
    JTextField jtf1=new JTextField(5);
    JTextField jtf2=new JTextField(5);
    ButtonGroup jbg=new ButtonGroup();
    JRadioButton jrb1=new JRadioButton("+");
    JRadioButton jrb2=new JRadioButton("-");
    JRadioButton jrb3=new JRadioButton("*");
    JRadioButton jrb4=new JRadioButton("/");
    JButton jb=new JButton("=");
    JLabel jl=new JLabel();
    public Application1() {
    this.setSize(400,300);
    this.setResizable(false);
    this.setLocation(this.getToolkit().getScreenSize().width/2-this.getWidth()/2,this.getToolkit().getScreenSize().height/2-this.getHeight()/2);
    this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    contentPanel.setLayout(new FlowLayout());
    contentPanel.add(jtf1);
    contentPanel.add(jp);
    jp.add(jrb1);
    jp.add(jrb2);
    jp.add(jrb3);
    jp.add(jrb4);
    jbg.add(jrb1);
    jbg.add(jrb2);
    jbg.add(jrb3);
    jbg.add(jrb4);
    jrb1.setSelected(true);
    contentPanel.add(jtf2);
    contentPanel.add(jb);
    contentPanel.add(jl);
    jb.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        myDO(e);
      }
    });
    this.setVisible(true);
    }public void myDO(ActionEvent e) {
    double d1,d2;
    String d3="";
    java.text.DecimalFormat df=new java.text.DecimalFormat(".###");
    try {
      d1=Double.parseDouble(this.jtf1.getText());
      d2=Double.parseDouble(this.jtf2.getText());
      if(jrb1.isSelected())
        d3=df.format(d1+d2);
      if(jrb2.isSelected())
        d3=df.format(d1-d2);
      if(jrb3.isSelected())
        d3=df.format(d1*d2);
      if(jrb4.isSelected())
        d3=df.format(d1/d2);
      this.jl.setText(d3);
    }catch(Exception ex) {
      JOptionPane.showMessageDialog(this,"两个输入框必须输入数字!","ERROR",JOptionPane.ERROR_MESSAGE);
      return;
    }
    }public static void main(String args[]) {
    new Application1();
    }
    }