2

我有一个我正在尝试制作的国际象棋游戏,我正在尝试repaint()在游戏循环中调用我的一个 JFrame 上的方法。这个特殊的 JFrame 显示了每个玩家的总击杀数。我很确定repaint()实际上是在调用它,但由于某种原因,它似乎没有正确更新我的 JLabels,它应该保存每个玩家的击杀数。

这是我的自定义 JFrame 扩展类的代码,其中包含代表杀戮的 JLabel。

private ChessGame game;
private JPanel killsPanel;
private String p1kills;
private String p2kills;
private JLabel kills;
private JLabel p1, p2;
private JLabel p1NumKills = new JLabel();
private JLabel p2NumKills = new JLabel();


//the player's kill values are increasing and registering, just not within the jlabels representing them
public KillsFrame(ChessGame game){
    this.game = game;
    killsPanel = new JPanel(new MigLayout("", "[center][right][left][c]", "[top][center][b]"));
    kills = new JLabel("KILLS");
    p1 = new JLabel(game.getCurrentPlayer().getName() + " - ");
    p2 = new JLabel(game.getOtherPlayer().getName() + " - ");

    //this is the part that should be working but isn't.
    //p1kills and p2kills aren't being updated or something.
    p1kills = "" + game.getCurrentPlayer().getKills();
    p2kills = "" + game.getOtherPlayer().getKills();
    p1NumKills.setText(p1kills);
    p1NumKills.setText(p2kills);

    killsPanel.add(kills, "span");
    killsPanel.add(p1);
    killsPanel.add(p1NumKills, "wrap");
    killsPanel.add(p2);
    killsPanel.add(p2NumKills, "wrap");

    killsPanel.setBackground(Color.lightGray);
    add(killsPanel);
    pack();
    setTitle("Scoreboard");
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    setResizable(true);
    setVisible(true);
    setLocationRelativeTo(null);
}

然后我只是在不同类的 main 方法中调用这个框架的 repaint() :

public static void main(String[] args) throws InterruptedException {

    JFrame gameFrame = new ChessMain();
    gameFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    gameFrame.pack();
    gameFrame.setResizable(true);
    gameFrame.setLocationRelativeTo(null);
    gameFrame.setVisible(true); 
    gameFrame.setTitle("Chess X");

    LoginFrame loginFrame = new LoginFrame(((ChessMain) gameFrame).getGame());

    System.out.println(((ChessMain) gameFrame).getGame().toString());
    System.out.println(((ChessMain) gameFrame).getGame().currentPlayer.getName()+ ", it's your turn.");

    //this is what creates the kills frame.
    KillsFrame kf = new KillsFrame(((ChessMain) gameFrame).getGame());

    while(true){

        ((ChessMain) gameFrame).getGame().run();
        kf.repaint();//*************************************
        Thread.sleep(1);

    }

}

非常感谢任何和所有帮助。

4

1 回答 1

1

当您尝试“睡眠”您的主线程时,您的错误就出现了。如果不使您的 GUI 无响应,这势必会导致错误。您最好的选择是使用 swing.Timer 类(此处为教程http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html)。定期触发事件以重新绘制()。这将产生流畅的动画。

如果由于某种原因您必须在 Swing 程序中休眠一个线程,请使用 SwingWorker 类创建一个新线程(而不是其他)。见http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html#process(java.util.List )

于 2012-06-25T08:23:26.510 回答