gpt4 book ai didi

java - 尝试更新记分牌 - Java

转载 作者:行者123 更新时间:2023-11-30 08:16:59 26 4
gpt4 key购买 nike

我正在为学校开发一个俄罗斯方 block 项目,当我试图在我的分数增加时更新记分板时,我偶然发现了一个问题。到目前为止,当我开始游戏时它会添加分数,但当分数增加时监听器不会更新。我正在与一个 friend 同时开发另一个 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;
}

谢谢:)

最佳答案

如果您在 EDT,您只需从 checkForFullLine() 调用即可

boardChanged() 

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

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

关于java - 尝试更新记分牌 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29512878/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com