我正在重新創建一個非常差的版本的cookie答題器只是爲了測試我的技能。那麼我遇到了一個問題,我無法弄清楚如何每3秒重複一次循環。 主類代碼:雖然循環 - 定時
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JFrame;
public class CookieClickerGame {
private static final int FRAME_WIDTH = 200;
private static final int FRAME_HEIGHT = 200;
public static void main(String[] args) {
JPanel panel = new JPanel();
JFrame frame = new JFrame();
JButton cookie = new JButton("Cookie");
JButton grandma = new JButton("Grandma");
JButton robot = new JButton("Robot");
panel.add(cookie);
panel.add(grandma);
panel.add(robot);
frame.add(panel);
/*----------------------------------------/
/ Buttons /
/----------------------------------------*/
ActionListener listener = new CookieClicker();
cookie.addActionListener(listener);
ActionListener listener2 = new CookieClicker();
grandma.addActionListener(listener2);
ActionListener listener3 = new CookieClicker();
robot.addActionListener(listener3);
/*---------------------------------------------------------/
/ Frame /
/---------------------------------------------------------*/
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
監聽器代碼:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class CookieClicker implements ActionListener {
static int cookies;
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("Cookie")) {
cookies++;
System.out.print('\f');
System.out.println(cookies + " Cookies");
} else if (event.getActionCommand().equals("Grandma") && cookies >= 10) {
System.out.println("+1 Grandma | -10 Cookies");
cookies = cookies - 10;
System.out.println(cookies + " Cookies");
while (true) {
cookies = cookies + 1;
System.out.print('\f');
System.out.println(cookies + " Cookies");
Thread.sleep(3000);
}
} else if (event.getActionCommand().equals("Robot") && cookies >= 50) {
System.out.println("+1 Robot | -50 Cookies");
cookies = cookies - 50;
System.out.println(cookies + " Cookies");
cookies = cookies + 1;
System.out.print('\f');
System.out.println(cookies + " Cookies");
} else {
JOptionPane.showMessageDialog (null, "Not Enough Cookies", "You're Poor", JOptionPane.INFORMATION_MESSAGE);
}
}
}
的Thread.sleep(3000)
不工作,這有什麼錯呢?
定義「不工作」。 – John3136
請看[如何使用Swing Timers](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html)[示例](http://stackoverflow.com/questions/ 18332135/java-for-loop-in-gui-textarea/18332315#18332315) – MadProgrammer
用try..catch surrond它開始 –