为什么我的.isSelected()方法不起作用?

时间:2015-01-15 15:46:17

标签: java methods awt actionlistener

我正在尝试做的是更改JRadioButton的文本,当他们被选中时,我让他们改变颜色。我知道我可以通过将代码更改为特定于每个按钮的专用事件处理方法中的文本来实现,但是我该如何操作以便使用一个只更改按钮的不同事件处理方法?我已经创建了一个,但它不起作用,这是代码:

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


public class LessonTwenty extends JFrame implements ActionListener{

JRadioButton b1,b2;
JTextArea t1;
JScrollPane s1;
JPanel jp = new JPanel();

public LessonTwenty()
{


     b1= new JRadioButton("green"); 
    b1.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            jp.setBackground(Color.GREEN);
        }
      });
     b2= new JRadioButton("red"); 
        b2.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                jp.setBackground(Color.RED);
            }
          });


        //Method to change the text of the JRadion Buttons, what i'm trying to make work
           new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                 if(b1.isSelected()){
                        b1.setText("Welcome");
                    }
                    else if(b2.isSelected()){
                        b2.setText("Hello");
                    }
            }
          };





    jp.add(b1);
    jp.add(b2);
    this.add(jp);

    setTitle("Card");  
    setSize(700,500);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
}


public static void main(String [ ] args){


    new LessonTwenty();


}


@Override
public void actionPerformed(ActionEvent e) {


}

}

2 个答案:

答案 0 :(得分:1)

如果我理解你,你想要做这样的事情:

//Method to change the text of the JRadion Buttons, what i'm trying to make work
     ActionListener al = new ActionListener() {

        public void actionPerformed(ActionEvent e) {

             if(b1.isSelected()){
                    b1.setText("Welcome");
                }
                else if(b2.isSelected()){
                    b2.setText("Hello");
                }
        }
      };

b1= new JRadioButton("green"); 
b1.addActionListener(al);
b2= new JRadioButton("red"); 
b2.addActionListener(al);

即。您定义了一个ActionListener,您可以在所有对象中使用它。

您在原始代码中定义的匿名对象绝对没有任何内容,它只创建一个无人访问的ActionListener,因为它没有分配给任何Button。

答案 1 :(得分:0)

也许这可以帮助

ActionListener al = new ActionListener() {

    public void actionPerformed(ActionEvent e) {

            if(e.getSource() == b1){
                b1.setText("Welcome");
            } else if(e.getSource() == b2){
                b2.setText("Hello");
            }
    }
  };
相关问题