问题
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,
edit: thanks everyone for the quick responses, my explanation wasn't very clear.
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.
回答1:
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
}
});
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.
来源:https://stackoverflow.com/questions/41069817/making-an-action-listener-for-a-jbutton-as-a-method