问题描述
如何将这个 ActionListener
变成用于特定 JButton
的方法?
(我知道有可能将其全部扔进一个方法中,但是。.hm。)
How can I make this ActionListener
into a method for a specific JButton
?
(im aware its possible to throw it all in an method but yeah..hm.)
myJButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
//do stuff
}
});
thx y'all,
thx y'all,
编辑:感谢大家的快速反应,我的解释不是很清楚。
edit: thanks everyone for the quick responses, my explanation wasn't very clear.
我调查了lambda的使用,这几乎是我在想的,尽管其他方式也很不错。
I looked into the use of lambdas and it was pretty much what I was thinking of, though the other ways are great to know aswell.
myButton.addActionListener(e -> myButtonMethod());
public void myButtonMethod() {
// code
}
再次感谢大家。
下次我将尝试变得更加清晰和快捷。
Thank you again, everyone.
I'll try to be more clear and quicker next time.
推荐答案
同样,您的问题仍然不清楚。您在上面的代码具有一种方法,可以将该代码放入其中:
Again, your question remains unclear. Your code above has a method, one that code can be put into:
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// you can call any code you want here
}
});
或者您可以从该方法中调用外部类的方法:
Or you could call a method of the outer class from that method:
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
button1Method();
}
});
// elsewhere
private void button1Method() {
// TODO fill with code
}
或者您可以从该代码中调用内部匿名类的方法
Or you could call a method of the inner anonymous class from that code
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
button1Method();
}
private void button1Method() {
// TODO fill with code
}
});
或者您可以使用lambda:
Or you could use lambdas:
button2.addActionListener(e -> button2Method());
// elsewhere
private void button2Method() {
// TODO fill with code
}
或者您可以使用方法引用:
Or you could use a method reference:
button3.addActionListener(this::button3Method);
// elsewhere
private void button3Method(ActionEvent e) {
// TODO fill with code
}
由您决定清楚您要执行的操作是什么以及阻止您执行此操作的原因。
Up to you to try to be clear on what exactly it is you're trying to do and what's preventing you from doing it.
这篇关于使JButton的动作侦听器作为方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!