我的程式是一個可以計時的記憶翻牌遊戲
在程式一些方法中建立一個新的 timer 並呼叫相應的 timertask
我的 timertask 以 inner class 寫在相同的 class 裡面
奇怪的是那方法就只有 timer & timertask 沒有執行,其他都順利執行
我懷疑是我用了 2個 timertask 做不同事情而沒有另外新增執行緒
以下為部分程式碼,請各位大大看看哪邊出問題,若資訊太少會在補充
謝謝
private JFrame mainFrame;
...
private List<JButton> Cards = new ArrayList<JButton>();
private List<Integer> numberlist = new ArrayList<Integer>();
private int firstOpenCard = -1; // 記錄第一次翻開的牌
private int openCards = -1; // 記錄翻開幾組
private Timer timer, timer2; // timer2 用來設定翻錯的牌多久蓋回,沒有順利執行
private int i1;
public MemoryGame(String title) {
playerTable = new JPanel();
playerArea = new JPanel();
playerInformation = new JPanel();
...
mainFrame = new JFrame(title);
playerInformation.add(clicks);
playerInformation.add(time);
clickDetermine clickCards = new clickDetermine(); //替每個按鈕加上事件
startBtn = new JButton("start");
startBtn.addActionListener(
new ActionListener () {
public void actionPerformed(ActionEvent arg0) {
if ( (openCards != CardNumber/2) && (openCards != -1) ) {
timer.cancel();
int option = JOptionPane.showConfirmDialog(null,
"Do you want to restart the game ?", "Confirm",
JOptionPane.YES_NO_CANCEL_OPTION);
if (option == 1 || option == 2) {
timer = new Timer();
timer.schedule(new timeDisplay(), 0, 1000);
return;
}
}
...
timer = new Timer();
timer.schedule(new timeDisplay(), 0, 1000);
}
});
giveUpBtn = new JButton("give up");
giveUpBtn.addActionListener(...);
...
private class clickDetermine implements ActionListener {
public void actionPerformed(ActionEvent e) {
useSteps++;
for (int i = 0 ; i < CardNumber ; i++) {
if (e.getSource() == Cards.get(i)) {
// 翻的是第一張, 記錄位置
if (firstOpenCard == -1) {
Cards.get(i).setText(numberlist.get(i) + "");
firstOpenCard = i;
clicks.setText("目前翻動次數 : " + useSteps);
}
else {
if (i == firstOpenCard) { // 翻同一張
useSteps