【问题标题】:Setting java awt mouse event without creating class?在不创建类的情况下设置java awt鼠标事件?
【发布时间】: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

标签: java swing awt


【解决方案1】:

没有办法创建一个类。这是 Java 的强类型所要求的。但是,您确实有一些选择可能比其他选择更好。

  • 您可以直接创建 lambda 函数。
  • 您可以拥有兼容的方法签名并将其用作 lambda 函数。
  • 您可以在顶级类中实现监听器,即。 CircleDraw 实现了 WindowListener。
  • 您可以在 CircleDraw 中声明一个字段并使其成为匿名类的实例。
  • 您可以使用匿名类作为参数(根据您的示例)
  • 您可以使用命名的内部类(您说过您不喜欢那样)。

它们都只是语法糖。在幕后,总有一个实现 WindowAdapter 的类。

【讨论】:

    猜你喜欢
    • 2012-01-21
    • 1970-01-01
    • 2010-10-23
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    相关资源
    最近更新 更多