2

我正在学习 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 坐标,以获得它自行移动的效果,即没有用户交互。我不太确定如何做到这一点,我想我需要某种 repaint() 方法来为每次更新重绘 JLabel 的位置。但是我如何让这个类知道它需要更新位置?

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

编辑: 请看我上面的编辑代码

4

2 回答 2

4

You will have to create a separate Thread that would modify the location of your label and then call validate() and repaint() on the container (frame.getContentPane()). Don't forget to put some sleep() value inside the thread.

However, there would be a better approach to create a separate JPanel. Inside it you would override the paintComponent method or the paint method and there you would draw an image instead of moving JLabels around.

于 2012-11-21T13:24:37.083 回答
1

You should better add a JPanel instead of the label to your layout. Choose the dimensions of the JPanel so that it can contain your car in every phase.

Then overwrite the paint method of that panel to position the image on it.

于 2012-11-21T13:24:21.370 回答