[問題] inner class 沒有執行

作者: obelisk0114 (追風箏的孩子)   2015-12-11 22:28:23
我的程式是一個可以計時的記憶翻牌遊戲
在程式一些方法中建立一個新的 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
作者: AI3767 (AIIA)   2015-12-11 23:11:00
翻錯 那邊, 一schedule完就cancel不會有問題嗎?不清楚你的timer2還有做什麼其它的, 如果不cancel可以嗎?另外是,這裡沒看到clickCards變數有被誰用呃 是報什麼錯??
作者: jinn (阿昌)   2015-12-12 21:10:00
timer2.cancel()刪掉 然後coverback那裡改成if(firstOpenCard!=-1) {Cards.get(firstOpenCard).setText("*"); }不就好了@@?
作者: AI3767 (AIIA)   2015-12-12 22:11:00
這個報錯和timer無關, 是程式邏輯要修, 你的寫法,遇到連續開牌, 可能也會有問題上面這句, 這樣做是好的, 在new coverback時傳入誰要翻回timer new一次就夠了. 然後連續翻牌問題, 可以有兩種方法1:最多翻兩張, 兩張有中,或是兩張都翻回後, 才能翻下一輪2:可連續翻牌,但自己定出方法和資料結構, 能記得哪兩張要互相配對比較也可以,原先的firstOpenCard也可以,只要能確保一次最多只會翻開兩張. 然後程式執行的部份再檢查看看吧

Links booklink

Contact Us: admin [ a t ] ucptt.com