为 JButton 创建一个动作监听器作为一种方法?
Making an Action Listener for a JButton as a method?
如何将此 ActionListener
变成特定 JButton
的方法?
(我知道它可以把它全部扔进一个方法但是是的..嗯。)
myJButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
//do stuff
}
});
谢谢大家,
编辑:感谢大家的快速回复,我的解释不是很清楚。
我研究了 lambda 的使用,这几乎是我的想法,尽管知道其他方法也很不错。
myButton.addActionListener(e -> myButtonMethod());
public void myButtonMethod() {
// code
}
再次感谢大家。
下次我会尽量说得更清楚、更快速。
同样,您的问题仍然不清楚。您上面的代码 有 一个方法,该代码可以放入:
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// you can call any code you want here
}
});
或者您可以从该方法调用外部 class 的方法:
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
button1Method();
}
});
// elsewhere
private void button1Method() {
// TODO fill with code
}
或者您可以从该代码
调用内部匿名方法 class
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
button1Method();
}
private void button1Method() {
// TODO fill with code
}
});
或者你可以使用 lambdas:
button2.addActionListener(e -> button2Method());
// elsewhere
private void button2Method() {
// TODO fill with code
}
或者您可以使用方法参考:
button3.addActionListener(this::button3Method);
// elsewhere
private void button3Method(ActionEvent e) {
// TODO fill with code
}
由您来尝试弄清楚您到底想做什么以及是什么阻止您这样做。
如何将此 ActionListener
变成特定 JButton
的方法?
(我知道它可以把它全部扔进一个方法但是是的..嗯。)
myJButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
//do stuff
}
});
谢谢大家,
编辑:感谢大家的快速回复,我的解释不是很清楚。
我研究了 lambda 的使用,这几乎是我的想法,尽管知道其他方法也很不错。
myButton.addActionListener(e -> myButtonMethod());
public void myButtonMethod() {
// code
}
再次感谢大家。
下次我会尽量说得更清楚、更快速。
同样,您的问题仍然不清楚。您上面的代码 有 一个方法,该代码可以放入:
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// you can call any code you want here
}
});
或者您可以从该方法调用外部 class 的方法:
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
button1Method();
}
});
// elsewhere
private void button1Method() {
// TODO fill with code
}
或者您可以从该代码
调用内部匿名方法 classbutton1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
button1Method();
}
private void button1Method() {
// TODO fill with code
}
});
或者你可以使用 lambdas:
button2.addActionListener(e -> button2Method());
// elsewhere
private void button2Method() {
// TODO fill with code
}
或者您可以使用方法参考:
button3.addActionListener(this::button3Method);
// elsewhere
private void button3Method(ActionEvent e) {
// TODO fill with code
}
由您来尝试弄清楚您到底想做什么以及是什么阻止您这样做。