简体   繁体   English

我可以在主要方法或任何方法中添加ActionListener()吗?

[英]Can i add an ActionListener() inside a main method or any method?

public void Message() {
@Override
public void actionPerformed(ActionEvent e) {
    JOptionPane.showMessageDialog(null, "Hello it is working");
}

}

//Message() is a method inside a class. // Message()是类内部的方法。

All methods must be declared inside a class separately. 所有方法必须在一个类中分别声明。 In simple terms, methods are something the object of a certain class can do, and defining them inside another method does not make sense. 简单来说,方法是某个类的对象可以做的事情,而在另一个方法中定义它们是没有意义的。 So in your case, 所以就你而言

public void Message (){

}
@Override
public void actionPerformed(ActionEvent e){
    JOptionPane.showMessageDialog(null, "Hello it is working");
}

Edit: This post is worth a read. 编辑:这篇文章值得一读。 I have no knowledge about lambda expressions, but it could be what you're looking for :) Does Java support inner / local / sub methods? 我对lambda表达式一无所知,但这可能正是您在寻找的东西:) Java是否支持内部/本地/子方法?

In Java, nested methods are not allowed! 在Java中,不允许使用嵌套方法!

In order to override actionPerformed method, you need to implement the ActionListener interface. 为了override actionPerformed方法,您需要implement ActionListener接口。

No. We cannot create nested methods in java. 不能。我们无法在Java中创建嵌套方法。 Try reading about actionlisteners . 尝试阅读有关动作侦听器的信息 :) :)

Since Java 8 methods can be nested using lambdas. 由于Java 8方法可以使用lambda嵌套。 Can methods in java be nested[...]? Java中的方法可以嵌套吗[...]? No, that's not possible. 不,那不可能。

The closest thing you can get is: 您可以获得的最接近的是:

class Name {
    void methodOne() {
        class InnerClass {
           void methodTwo() {
           }
         }
     }
 }

That is, a second method defined in a inner class defined in a method. 即,在方法中定义的内部类中定义的第二种方法。

You can declare the method static inside the inner class, so you do not have to call new 您可以在内部类内部将方法声明为静态,因此不必调用new

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

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