2017-05-06 41 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

不幸的是,我不能,虽然我想我找到了解决方案,我会发布它,如果我能够 –

相关问题