每次更新时移动 JLabel 的位置



我正在学习Swing,我有以下代码:

public class SimView {
private JFrame frame;
private JLabel background;
private JPanel car_panel;
public SimView() {
    frame = new JFrame("GUI");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 500);
    frame.getContentPane().setLayout(null);
    background = new JLabel("");
    background.setIcon(new ImageIcon(
            "C:\Users\D__\Desktop\background.png"));
    background.setBounds(0, 0, 384, 462);
    frame.getContentPane().add(background);
    frame.setVisible(true);
    car_panel = new JPanel();
    car_panel.setBounds(175, 430, 16, 21);
    car_panel.setVisible(true);
    car_panel.setBackground(Color.BLACK);
    background.add(car_panel);
    MoveCarRunnable carMover = new MoveCarRunnable(car_panel);
}
private static class MoveCarRunnable implements Runnable {
    private JPanel car;
    MoveCarRunnable(final JPanel car) {
        this.car = car;
    }
    @Override
    public void run() {
        // Should I call rePaint() on the car_panel here then ? 
    }
}

我想做的是在每次更新时移动名为"car"的 JLabel 的 y 坐标,以获得它自己移动的效果,即没有用户交互。我不太确定如何做到这一点,我想我需要某种 repaint() 方法为每次更新重绘 JLabel 的位置。但是我如何让这个类知道它需要更新位置呢?

任何指针(链接/代码)将不胜感激。我想了解 Swing 及其组件在这种情况下如何工作的概念,而不仅仅是采用解决方案,但我当然对解决方案感兴趣,以便我可以更仔细地研究它。谢谢

编辑:请参阅上面的编辑代码

您必须创建一个单独的Thread来修改标签的位置,然后在容器上调用validate()repaint()frame.getContentPane())。不要忘记在线程中放置一些sleep()值。

但是,会有更好的方法来创建一个单独的JPanel。在其中,您将覆盖paintComponent方法或paint方法,在那里您将绘制图像而不是移动JLabel

最好在

布局中添加JPanel而不是标签。选择JPanel的尺寸,以便它可以在每个阶段容纳您的汽车。

然后覆盖该面板的 paint 方法以将图像放置在其上。

最新更新