2017-05-06 42 views
0

我想在一個類中使2個單選按鈕工作,這樣當它們被選中時它將允許按下另一個類中的JButtons。Java如何使用單選按鈕來啓動一個動作,並能夠點擊另一個按鈕

換句話說,如果我不按單選按鈕,我不能按在其他類的按鈕和改變按鈕的顏色在其他類。

我沒有代碼,但我在想添加多個動作偵聽器的兩個類,我想getter和setter方法,但什麼也沒有發生,我不能使它發揮作用。

我試圖用一個字符串從單選按鈕,例如:

If(btn.equals("w")){ 

Some string = "w" 

}else{ 

Some string = "b" 

} 

,然後設置字符串,並把它在其他類,但不能正常工作。有沒有辦法讓你的工作在你按下兩個單選按鈕之一,然後其他JButton可以點擊?你會怎麼做?

回答

0

此代碼將啓用所有第二組中的單選按鈕一旦任何第一組的單選按鈕的選擇變得。

public class RadioButtonDemo extends JFrame { 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       new RadioButtonDemo().setVisible(true); 
      } 
     }); 
    } 

    public RadioButtonDemo() { 
     super("Swing JRadioButton Demo"); 

     JRadioButton option1 = new JRadioButton("Linux 1"); 
     JRadioButton option2 = new JRadioButton("Windows 1"); 
     JRadioButton option3 = new JRadioButton("Macintosh 1"); 

     JRadioButton option4 = new JRadioButton("Linux 2"); 
     JRadioButton option5 = new JRadioButton("Windows 2"); 
     JRadioButton option6 = new JRadioButton("Macintosh 2"); 

     ButtonGroup group1 = new ButtonGroup(); 
     ButtonGroup group2 = new ButtonGroup(); 

     ActionListener listener = new AbstractAction() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       if (((JRadioButton) e.getSource()).isSelected()) { 
        Enumeration<AbstractButton> elements = group2.getElements(); 
        while (elements.hasMoreElements()) { 
         JRadioButton button = (JRadioButton) elements.nextElement(); 
         button.setEnabled(true); 
        } 
       } 
      } 
     }; 

     option1.addActionListener(listener); 
     option2.addActionListener(listener); 
     option3.addActionListener(listener); 

     option4.setEnabled(false); 
     option5.setEnabled(false); 
     option6.setEnabled(false); 

     group1.add(option1); 
     group1.add(option2); 
     group1.add(option3); 

     group2.add(option4); 
     group2.add(option5); 
     group2.add(option6); 

     setLayout(new FlowLayout()); 

     add(option1); 
     add(option2); 
     add(option3); 

     add(option4); 
     add(option5); 
     add(option6); 


     pack(); 
    } 
} 

在更改按鈕顏色的代碼中,您可能會首先檢查是否已啓用該按鈕。或者,如果這是通過UI元素完成的,則可以根據需要禁用該元素。

+0

這很好,但很可能你已經猜到了,我是一個小白,將JButton是另一個類,我必須使用ActionListen繼承得到的JButton中的其他類的工作? –

+0

難道你不能在這個類中創建一個你可以從這裏調用的方法嗎? 如果不是,你能提供一個SSCCE嗎? https://meta.stackexchange.com/questions/22754/sscce-how-to-provide-examples-for-programming-questions – Dalendrion

+0

不幸的是,我不能,雖然我想我找到了解決方案,我會發布它,如果我能夠 –

相關問題