gpt4 book ai didi

java - 如何解决 Swing JPanel 中显示倒数计时器(JLabel)的延迟问题

转载 作者:行者123 更新时间:2023-12-02 08:08:53 25 4
gpt4 key购买 nike

我已经实现了一个倒计时器(在函数中),它每秒更新 Swing 面板中的标签,这是代码:

public void DefineTimer()
{
Action updateClockAction = new AbstractAction() {
public void actionPerformed(ActionEvent e){

JPanelMainGame.this.jLabelSeconds.setText(Integer.toString(JPanelMainGame.this.m_TimerTotalSeconds));
JPanelMainGame.this.jLabelSeconds.setFont(new java.awt.Font("Lucida Handwriting", 1, 36));
JPanelMainGame.this.jLabelSeconds.setForeground(Color.red);
JPanelMainGame.this.jLabelSeconds.setVisible(true);



if( JPanelMainGame.this.m_TimerTotalSeconds >0)
{
JPanelMainGame.this.m_TimerTotalSeconds--;
}
else if ( JPanelMainGame.this.m_TimerTotalSeconds == 0)
{

JPanelMainGame.this.m_Timer.stop();
JPanelMainGame.this.jLabelSeconds.setText("0");
System.out.println("!m_WasGameDecisived: "+!m_WasGameDecisived);

JPanelGameApplet gameApplet = (JPanelGameApplet) getTopLevelAncestor();
//Checking whether time ended for both players and no solution was recieved

if(gameApplet.GetJPanelChooseGame().GetGameType() == eGameType.Net)
{


gameApplet.GetClinetThread().UpdateServerOfTimeEnded();

if (!m_WasGameDecisived)
{
//
System.out.println("Tie - No one had a solution in the given time");

System.out.println("Before send request to solve - Is Socket Closed:"+((JPanelGameApplet)
gameApplet.GetClinetThread().SendRequestToClosePlayerThreadAndRemoveItFromPlayersOnServer();

((JPanelGameApplet)getTopLevelAncestor()).GetDJ().stop();
Menu.BrowseTo(PanelMenuNumber.k_ChooseGame, JPanelMainGame.this.getParent());
((JPanelGameApplet)getTopLevelAncestor()).GetDJ().play(0);

}
}
else if(gameApplet.GetJPanelChooseGame().GetGameType() == eGameType.Single)
{
JPanelMainGame.this.showPopUpSelectionBar();

}

}

((JPanelGameApplet)getTopLevelAncestor()).GetNetMainGame().Initialize();

}
};
m_Timer = new Timer(1000, updateClockAction);
}

现在,当我想要执行以下操作时,我的问题出在代码的另一部分:

case ProtocolMessages.k_StartGame:
m_GameApplet.GetJpanelStartNetGame().DefineTimer();
m_GameApplet.GetJpanelStartNetGame().GetTimer().start();
m_GameApplet.ShowBoardToSolve();
Menu.BrowseTo(PanelMenuNumber.k_NetPlayersGameStart,m_GameApplet.GetJPanelNetGameSetting().getParent());
m_GameApplet.GetDJ().Next();
break;

所以问题是当我想开始游戏时,我正在定义我的计时器并分配它,给它启动命令并转到屏幕,我应该在那里看到计时器(JLabel 更新)。
尽管它应该已经在计数了(甚至在显示计时器的屏幕之前),但我仍然有延迟:我看到显示计时器的面板,大约两秒后,Jlabel 出现并开始倒计时。
我认为这是因为在我执行 Jlabel.setText() 时,事件调度线程没有立即更新 Jlabel

关于如何在不延迟显示 Jlabel 的情况下开始游戏有什么建议吗?
谢谢

最佳答案

从线程中调用 SwingUtilities.invokeAndWait 以设置标签文本。

关于java - 如何解决 Swing JPanel 中显示倒数计时器(JLabel)的延迟问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7741506/

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