gpt4 book ai didi

java - 使用java中的线程通过标签进行 move 运动

转载 作者:行者123 更新时间:2023-12-01 14:14:50 29 4
gpt4 key购买 nike

我在制作台球游戏时遇到问题,当我模拟击球时,我需要球使用react,程序是这样工作的,您单击击球的方向和力量,然后单击开始, go按钮位于创建标签的GUI类中,该按钮调用我的主类中的一个方法来接收参数,然后在其中一段时间​​,改变球的X和Y,直到功率减小到0然后停止,代码正在工作,但球会 move 直到 while 停止。所以 while 起作用,当 power int 为 0 时, while 熄灭,然后绘制新的 X,Y。

这是按钮调用的函数,按钮发送所有参数

 public void golpe(int pbola, int pvelocidad, String pdireccion, JLabel[] listalabels) throws InterruptedException{

listabolas[pbola].setVelocidad(pvelocidad);
listabolas[pbola].setDireccion(pdireccion);

while (listabolas[pbola].getVelocidad() > 0) {

moverBola(pbola, listalabels);

//System.out.println(listabolas[pbola].getPosX());
//System.out.println(listabolas[pbola].getPosY());

Thread.sleep(500);

//This line is supposed to change the X and Y of the object over and over
//but only does it till the end
listalabels[pbola].setLocation(listabolas[pbola].getPosX(), listabolas[pbola].getPosY());
}

}

这里是函数 moverola(),只复制了一个“if”,让代码看起来不那么大

private void moverBola(int pbola, JLabel[] listalabels) {

if (listabolas[pbola].getDireccion().equals("SE")) {

int pposX = listabolas[pbola].getPosX();
listabolas[pbola].setPosX(pposX + 1);


int pposY = listabolas[pbola].getPosY();
listabolas[pbola].setPosY(pposY + 1);


}

最佳答案

Swing 是一个单线程框架。也就是说,与 UI 的所有交互都应该在单个线程(称为事件调度线程)内发生。

任何阻止该线程的操作都将阻止 EDT 更新屏幕或处理任何新事件。

您的 while-loop 正在阻止 EDT,从而阻止它在 while-loop 完成之前绘制任何更新。

看看Concurrency in Swing了解更多详情。

您可以采取多种方法...

您可以使用Thread,但这会导致问题,因为您需要确保对 UI 所做的任何更改都重新同步回 EDT,这可能会变得困惑......

对于example

您可以使用按固定时间间隔滴答的javax.swing.Timer,并且可以从其分配的ActionListener 中更新任何内部参数。由于刻度事件发生在 EDT 内,因此可以从其中更新屏幕。

对于example

您可以使用 SwingWorker 在后台运行任务。它具有将更新重新同步回 EDT 的方法,但对于您的目的来说可能有点过头了......

更新了可能的Timer示例

警告 - 仅使用代码片段生成合理的示例是非常困难的,但是,像这样的东西可能会起作用

public void golpe(final int pbola, int pvelocidad, String pdireccion, final JLabel[] listalabels) throws InterruptedException{

listabolas[pbola].setVelocidad(pvelocidad);
listabolas[pbola].setDireccion(pdireccion);

Timer timer = new Timer(40, new ActionListener() {
public void actionPerformed(ActionEvent evt) {

if (listabolas[pbola].getVelocidad() == 0) {
((Timer)evt.getSource()).stop();
} else {
moverBola(pbola, listalabels);
}

}
});
timer.setRepeats(true);
timer.start();

}

关于java - 使用java中的线程通过标签进行 move 运动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18201557/

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