按钮单击调用不带参数的面板方法

时间:2020-12-19 23:19:18

I have JFrame and inside that I have JPanel and inside of that I have one button. And when I click I want it call some method with I specify. Is that somehow possible without parameters?

我有JFrame,里面有JPanel,里面有一个按钮。当我点击我希望它用我指定的方法调用一些方法。这是否可能没有参数?

This is how I have done it until now:

这就是我到现在为止所做的事情:

JFrame frame = new JFrame("");
JPanel container = new JPanel();
frame.add(container);

JButton button = new JButton("Button");
button.addActionListener( e -> mySpecialMethod());  // I have to create action performed method with has ActionEvent as parameter.

...

Is there a simpler way? It seems redundant to do it all the time. Something like button.addActionListener(Foo::bar); and public void bar(){....}

有更简单的方法吗?一直这样做似乎是多余的。像button.addActionListener(Foo :: bar);和public void bar(){....}

1 个解决方案

#1


You can use method reference here only if your method has an ActionEvent parameter:

仅当您的方法具有ActionEvent参数时,才可以在此处使用方法引用:

button.addActionListener( this::mySpecialMethod );

void mySpecialMethod( ActionEvent e ) { ... }

If your method has no parameter, then interface signature and method signature don't match, so you will have a compilation error. Probably that's a matter of taste, but for me e -> mySpecialMethod() looks not very redundant (especially compared to anonymous classes I had to use prior to Java 8).

如果您的方法没有参数,那么接口签名和方法签名不匹配,因此您将遇到编译错误。可能这是一个品味问题,但对我来说,e - > mySpecialMethod()看起来并不是多余的(特别是与我在Java 8之前必须使用的匿名类相比)。

#1


You can use method reference here only if your method has an ActionEvent parameter:

仅当您的方法具有ActionEvent参数时,才可以在此处使用方法引用:

button.addActionListener( this::mySpecialMethod );

void mySpecialMethod( ActionEvent e ) { ... }

If your method has no parameter, then interface signature and method signature don't match, so you will have a compilation error. Probably that's a matter of taste, but for me e -> mySpecialMethod() looks not very redundant (especially compared to anonymous classes I had to use prior to Java 8).

如果您的方法没有参数,那么接口签名和方法签名不匹配,因此您将遇到编译错误。可能这是一个品味问题,但对我来说,e - > mySpecialMethod()看起来并不是多余的(特别是与我在Java 8之前必须使用的匿名类相比)。