import javax.swing.*;
import java.awt.event.*;
import button.names.constants.Constants;
public abstract class FirstSwingExample implements ActionListener {
private static void drawFrame(JFrame frame) {
frame.setSize(800, 400);
frame.setLayout(null);
frame.setVisible(true);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
drawFrame(frame);
JButton button = new JButton(Constants.CLICK);
frame.add(button);
ActionListener actionListener = new CreateActionListener();
int xButtonPosition = ((frame.getWidth() / 2) - Constants.WIDTH / 2);
int yButtonPosition = ((frame.getHeight() / 2) - Constants.HEIGHT / 2);
button.addActionListener(actionListener);
button.setBounds(xButtonPosition, yButtonPosition, Constants.WIDTH, Constants.HEIGHT);
}
}
class CreateActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// need function here
}
}
我是 Java 新手。我想制作可重用的侦听器,我将在初始化侦听器时重用它。我来自 js
,在那里我可以传递参数,并在构造函数中获取它。
我怎样才能做同样的事情?或者有什么更好的方法可以在我的代码中实现它?
答案 0 :(得分:1)
在 Java 中,您可以使用 lambda 表达式,它类似于 JS 的“箭头函数”。因此,如果您想避免显式实例化 ActionListener
,您可以使用
button.addActionListener(e -> doSomethingWithE(e))
其中 doSomethingWithE
可以是任何表达式。
答案 1 :(得分:0)
我喜欢使用方法引用,不需要额外的类:
void someMethod() {
// ...
button.addActionListener(this::handleButton); // similar to (e -> handleButton(e))
// ...
}
private void handleButton(ActionEvent ev) {
// do something
}
动作监听器只是类,它们可以有带参数的构造函数:
class CreateActionListener implements ActionListener {
CreateActionListener(/* argument list */) {
// ...
}
public void actionPerformed(ActionEvent e) {
// need function here
}
}
甚至接受一个函数
class CreateActionListener implements ActionListener {
private Runnable function; // or Consumer<ActionEvent> function
CreateActionListener(Runnable function) {
this.function = function;
}
public void actionPerformed(ActionEvent ev) {
function.run(); // function.accept(ev)
}
}
并且你可以添加一个方法来改变函数:
class CreateActionListener implements ActionListener {
private Runnable function; // or Consumer<ActionEvent> function
// ...
public void setFunction(Runnable function) {
this.function = function;
}
}
也可以改变听众,但不确定
只是一些想法,我更喜欢第一个选项并且在方法内部有逻辑来处理操作(例如基于一些 enum
变量)