![](/img/trans.png)
[英]Why does my else statement execute in a 'while-loop' but does not execute in a 'for-loop' in JAVA
[英]Why does my if statement in my while loop only execute in debugging?
因此,我正在制作井字游戲,並在IntelliJ中使用由JButtons制作的GUI。 這是我當前的代碼,用於檢測何時按下按鈕並將其標記為X
或O
public static void taketurn(){
Boolean gamerunning = true;
while(gamerunning){
if(button1.getModel().isPressed()) {
button1.setText("X");
gamerunning = false;
}
}
}
我的問題是,在運行代碼時,它可以很好地創建UI,但是單擊按鈕無效。 但是,當我進入調試階段但在button1.setText("X")
處button1.setText("X")
,然后從那里前進時,它將正確執行代碼,並且出現X
為什么這僅在帶有中斷的調試中起作用而不能在正常運行中起作用?
全速運行時,可能不會發生,而while循環再次開始之前,if沒有執行。 您是否考慮過在按鈕上使用actionListener? 創建按鈕時嘗試這樣的操作
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//logic here to add X or O
}
}});
然后,您不必擔心要通過循環來等待用戶選擇。 只要他們按下按鈕,您的邏輯就會處理X或O的添加
我認為在這里使用ActionListener類是一個好主意。 您可以制作自己的ActionListener實現,而不必使用匿名類,如下所示:
class MyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
//The stuff you want to do when the button is pressed
}
}
然后,可以在需要時創建此類的新實例,並使用addActionListener(ActionListener l)函數將其添加到JButton中。
MyJButton.addActionListener(new MyActionListener());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.