2015-01-15 64 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