java为每次更新移动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及其组件在这种情况下是如何工作的,而不仅仅是采用一种解决方案,但当然我对一种解决方案感兴趣,这样我可以更深入地研究它。谢谢
编辑: 请看我上面的编辑代码
# 1 楼答案
您最好在布局中添加
JPanel
而不是标签。选择JPanel
的尺寸,以便在每个阶段都能容纳您的汽车然后覆盖该面板的
paint
方法,将图像定位到该面板上# 2 楼答案
您必须创建一个单独的
Thread
来修改标签的位置,然后在容器上调用validate()
和repaint()
(frame.getContentPane()
)。别忘了在线程中加入一些sleep()
值然而,有更好的方法来创建一个单独的
JPanel
。在它里面,你可以覆盖paintComponent
方法或paint
方法,在那里你可以画一个图像,而不是移动JLabel