簡體   English   中英

設置java awt鼠標事件而不創建類?

[英]Setting java awt mouse event without creating class?

我正在做awt工作,但是awt與以前學過的JavaFX相比並不容易,我正在努力為框架中的按鈕設置事件,並且我有一個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中是否有類似的功能可以做到這一點?

沒有辦法創建一個類。 Java的強類型要求這。 但是,您確實有一些選擇可能會比其他選擇更好。

  • 您可以直接創建lambda函數。
  • 您可以具有兼容的方法簽名,並將其用作lambda函數。
  • 您可以在頂級類中實現監聽器,即。 CircleDraw實現WindowListener。
  • 您可以在CircleDraw中聲明一個字段,並使它成為匿名類的實例。
  • 您可以使用匿名類作為參數(根據您的示例)
  • 您可以使用一個命名的內部類(您說自己不喜歡這樣)。

它們都只是語法糖。 在幕后,總是有一個實現WindowAdapter的類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM