2015-04-08 17 views
1

我正在爲學校開發一個Tetris項目,當我的分數增加時,我試圖讓scorboard更新時遇到了問題。截至目前,它在我開始遊戲時增加了分數,但當分數增加時,聽衆不會更新。我正在和一個朋友一起工作另一個Java項目,在那裏我們有一個類似的方法工作,但即使我試圖從該項目複製函數,我無法得到它的更新。試圖讓記分牌更新 - Java

得分函數:

private void scoreKeeper(int n) { 
    switch (n) { 
     case 1: 
      score += 100; 
      break; 
     case 2: 
      score += 300; 
      break; 
     case 3: 
      score += 500; 
      break; 
     case 4: 
      score += 800; 
      break; 
     default: 
      break; 
    } 
} 

public int getScore() { 
    System.out.println(score); 
    return score; 
} 

與框架:

class TetrisFrame extends JFrame implements BoardListener { 

private Board board; 
JLabel scoreLabel; 

@Override public void boardChanged() { 
     scoreLabel.setText("Score: " + board.getScore()); 
    } 

public TetrisFrame(Board board) { 
    super("Tetris"); 
    this.board = board; 
    JButton close = new JButton("Exit"); 
    this.scoreLabel = new JLabel("Score: " + board.getScore()); 
    JMenuBar menuBar = new JMenuBar(); 
    final TetrisComponent frame = new TetrisComponent(board); 

    JComponent.setDefaultLocale(Locale.ENGLISH); 
    Locale.setDefault(Locale.ENGLISH); 

    this.setJMenuBar(menuBar); 
    menuBar.add(close); 
    menuBar.add(scoreLabel); 

    close.addActionListener(e -> { 
     int selectedOption = JOptionPane.showConfirmDialog(null, "Do You want to close the game?\n" + "All progress will be lost!", 
       "Exit game", JOptionPane.YES_NO_OPTION); 
     if (selectedOption == JOptionPane.YES_OPTION) { 
      System.exit(0); 
     } 
    }); 

    this.setLayout(new BorderLayout()); 
    this.add(frame, BorderLayout.CENTER); 

    this.pack(); 
    this.setSize(frame.getPreferredX(board), frame.getPreferredY(board)); 
    this.setVisible(true); 
    this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 

    setFocusable(true); 
    frame.requestFocusInWindow(); 

    } 
} 

功能是記分牌更新:

private void checkForFullLine() { 
    boolean fullLine = false; 

    for (int h = 1; h < getHeight() - 1 ; h++) { 
     for (int w = 1; w < getWidth() - 1; w++) { 
      if (getSquares(w, h) == SquareType.EMPTY) { 
       fullLine = false; 
       break; 
      } 
      fullLine = true; 

     } 
     if (fullLine) { 
      amountOfFullLines += 1; 
      clearRow(h); 
      moveBoardDown(h); 
     } 
    } 
    scoreKeeper(amountOfFullLines); 
    amountOfFullLines = 0; 
} 

謝謝:)

+0

哪裏是更新的代碼記分牌?你已經展示了除此之外的一切。 – RealSkeptic

+0

噢,對不起:)現在有 – milkme

+0

更正我的答案,以適應更新 – notanormie

回答

1

如果你在美國東部時間你可以從暗示checkForFullLine()

boardChanged() 

否則,你可以調用GUI更新SwingUtilities.invokeLater,因爲你不能直接改變GUI從其它線程調用:

SwingUtilities.invokeLater(new Runnable() { 
    public void run() { 
     boardChanged(); 
    } 
}); 
+0

我有一個notifyListeners()函數那麼,我已經嘗試將它添加到scoreKeeper沒有任何結果:/ – milkme

+0

哦,等等,你說checkForFullLine ),很好地嘗試過,但結果相同。 – milkme

+1

這裏還有其他可能的錯誤。你也不會將俄羅斯方塊框架作爲聽衆添加到電路板上,所以無法通知它。至少不在提供的代碼中。 – notanormie