繁体   English   中英

我可以执行其他类方法执行的ActionListener方法actionPerformed吗?

[英]Can I execute ActionListener method actionPerformed from other class methods?

我有

ActionListener actionListenerRing = new ActionListener() {
              public void actionPerformed(ActionEvent actionEvent) {

在我的类构造函数中定义。 如何从main方法调用actionPerformed方法?

我只是想知道如果我可以直接从类的任何其他部分调用动作侦听器,或者我应该将动作侦听器的代码移动到其他方法,以便ActioListener和其他类方法都可以访问。

通常,您不会在未将侦听器附加到某物的情况下创建它。 因此,如果您的main方法必须直接调用此类ActionListener ,则可能是您的设计有问题。 也许您可以对自己想要实现的目标发表评论。

您可能希望阅读整个观察者设计模式 ,但简而言之,如果希望在执行操作时得到通知,可以将侦听器添加到另一个对象。 例如:

JButton button;//a button I obtained from somewhere and in 
// which I am interested
button.addActionListener( new ActionListener(){ 
  public void actionPerformed( ActionEvent actionEvent ){
     //do something with the fact that the button has been pressed
  }
});

在上面的示例中,按钮将在按下时通知我添加的ActionListener ,我可以通过将相关代码放置在actionPerformed方法中对此做出反应。 但是我不会自己打电话给我的听众。

actionListenerRing设为static (类)变量(假设main在同一类中),而不是构造函数的局部变量,则可以从main进行访问,并且可以将actionPerformed方法称为actionListenerRing.actionPerformed

但是我认为手动调用该方法不是一个好主意。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM