2015-01-15 63 views
0

那么我想要做的是改变JRadioButton的文本时,他们被选中,我让他们改变颜色。我知道我可以通过将代码更改为专用于每个按钮的专用事件处理方法中的文本来做到这一点,但我该如何执行,以便使用只改变按钮的不同事件处理方法?我已经创建了一个,但它不工作,下面的代码:为什么我的.isSelected()方法不起作用?

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) { 


} 

} 

回答

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。

+0

谢谢你,它的工作 – user4442652 2015-01-15 16:36:24

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"); 
      } 
    } 
    }; 
+0

谢谢你的反馈,这个工作太 – user4442652 2015-01-15 16:36:44