0
我正在做awt工作,但awt與JavaFX相比並不容易,我之前學習過,我在爲框架中的按鈕設置事件而掙扎,並且我有PlayAgain()方法,我的目標是調用方法當按鈕被點擊時。額外:請不要創建一個內部類來實現一些處理程序,並且使用awt而不是swing/Fx。在不創建類的情況下設置java awt鼠標事件?
這是我的代碼:
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類似的事情可以做這個?
「請不要創建一個內部類」 - 是_your_要求嗎?請注意,即使'e - > {/ *調用方法* /}'也會創建一個匿名內部類。對於動作偵聽器,您可以使用lambda表達式,例如'button.addActionListener(e - > {...})',用於像鼠標偵聽器這樣的其他偵聽器,因爲界面不符合要求(您可以提供儘管接受lambdas的某種形式的構建器)。 – Thomas
使用'Action',例如[(https://stackoverflow.com/a/37063037/230513);另請參閱[*初始線程*](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html)。 – trashgod