2013-11-01 38 views
0

我在写一个很大的类,不想在这里发布。问题是以下内容,我如何引用在不同类的构造函数中按下的按钮?比方说,我想在侦听器中执行一些操作后禁用它。如果监听器是anonymus或者是一个内部类SomeClass的,我只想用这样的变量名:从一个单独的类中的侦听器中禁用JButton

button.setEnabled(false); 

但我怎么能做到这一点时,我的听众是一个单独的类?尝试使用e.getModifiers()。setEnabled(false)和e.getSource()。setEnabled(false),没有工作。

public class SomeClass extends JPanel { 
    private JButton button = new JButton("Button"); 
    public SomeClass() { 
     button.setActionCommand("button"); 
     button.addActionListener(new ButtonListener()); 
    } 


    public static void main(String[] args) { 
     // TODO code application logic here 
    } 
} 
class ButtonListener implements ActionListener { 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     String src = e.getActionCommand(); 
     if (src.equals("button")) { 
      //some actions here 
      //then    
     }   
    }  
} 

回答

1

尝试此事件是指这个((JButton)e.getSource()).setEnabled(false)

必须工作)

e.getSource()回报组件(docs

+0

是的,它的工作,非常感谢你。尽管如此,在我看来,这个解决方案是某种“欺骗”。我想知道是否有这样的“官方”方式? –

+0

这不是一个欺骗它是官方的方法 – alex2410