试图让记分板更新 - Java

时间:2015-04-08 11:06:18

标签: java listener

我正在为学校制作一个俄罗斯方块项目,当我的分数增加时,我试图让scorboard更新时偶然发现了一个问题。截至目前,它在我开始游戏时添加了分数,但是当分数增加时,听众不会更新。我正在与朋友同时处理另一个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;
}

谢谢:)

1 个答案:

答案 0 :(得分:1)

如果你在EDT,你只需从checkForFullLine()

打电话
boardChanged() 

否则您可以使用SwingUtilities.invokeLater调用GUI更新,因为您不允许直接从其他线程更改GUI:

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