【发布时间】:2017-10-18 19:49:13
【问题描述】:
我正在做awt工作,但是与我之前学习的JavaFX相比,awt并不容易,我正在努力为框架中的按钮设置一个事件,并且我有一个PlayAgain()方法,我的目标是调用单击按钮时的方法。附加:请不要创建一个内部类来实现一些处理程序,并且只使用awt而不是swing/Fx。
这是我的代码:
public class CircleDraw extends Frame{
int[] diceResults;
public void paint(Graphics g) {
super.paint(g);
//in this part, I just using Graphics drawing some circles.
}
public void PlayAgain() {
//......do something
}
public static void main(String args[]) {
Frame frame = new CircleDraw();
Button button = new Button("again!");//this is the button, I want to set a Event, when clicking the button,my program will call PlayAgain() method
frame.add(button);
button.setBounds(5, 5, 5, 5);
frame.add(button);
frame.setLayout(new FlowLayout());
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
frame.setSize(500, 250);
frame.setVisible(true);
}
}
我记得在 JavaFX 中确实可以这样写:
button.setMouseClicked(e -> {
//call the method} )
那么在awt中是否有类似的东西可以做到这一点?
【问题讨论】:
-
“请不要创建内部类” - 这是您的要求吗?请注意,即使
e -> { /*call the method*/ }也会创建一个匿名内部类。对于动作侦听器,您可以使用 lambdas,即button.addActionListener( e -> { ... } ),对于其他侦听器(例如鼠标侦听器),由于接口不符合要求,因此不太容易(您可以提供某种形式的接受 lambdas 的构建器)。跨度> -
使用
Action,代表example;另见Initial Threads。