我正在尝试将由 JLabel 表示的机器人移动到 GridLayout 中。 移动已完成,但 JLabel 的显示仅针对最后的整理方 block 完成。 我希望看到从一个盒子到另一个盒子的移动。我该怎么办?
import java.awt.Color;
import java.awt.Component;
import java.awt.LayoutManager;
import java.io.Serializable;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.LayoutStyle;
// Robot
public class Robot extends Case implements Serializable {
private ImageIcon imageRobot;
private Color couleur;
public Robot () {
imageRobot = new ImageIcon("./assets/balle.png");
setIcon(imageRobot);
}
public void seDeplacer (JPanel panel, Vector<Case> listeDeCases) {
for (int i=0; i<5; i++) {
LayoutManager layout = panel.getLayout();
try { Thread.sleep(1000);
panel.remove(panel.getComponent(i));
panel.add(this, i);
panel.doLayout();
}
catch (InterruptedException e) {}
}
}
public void detruire () {
}
public void setCouleur (Color couleur) {
this.couleur=couleur;
}
public Color getCouleur () {
return this.couleur;
}
}
最佳答案
try { Thread.sleep(1000);
不要在 AWT 事件调度线程 (EDT) 上执行此操作。无法重绘您的 GUI,因为此代码阻止了它。
使用 javax.swing.Timer
(不要与任何其他 Timer
混淆)为下一次需要移动机器人设置事件。您将需要跟踪局部变量之外的状态。
关于java - 在 GridLayout java swing 中移动 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58866057/