Force444
Force444

Reputation: 3381

Moving a JLabel's position for every update

I'm learning Swing and I have the following code:

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 ? 

    }

}

What I want to do is to move the JLabel called "car" 's y coordinates for every update to get the effect of it moving by itself i.e. no user interaction. I'm not quite sure how to do this, I suppose I need to have some sort of repaint() method redrawing the position of the JLabel for every update. But how do I get this class to know that it needs to update the position?

Any pointers (links/code) would be appreciated. I want to get the concept of how Swing and its components work in this case, rather than just employing a solution but of course I am interested in a solution so I can study it closer. Thanks

EDIT: Please see my edit code above

Upvotes: 2

Views: 901

Answers (2)

Dan D.
Dan D.

Reputation: 32391

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.

Upvotes: 4

Kai
Kai

Reputation: 39651

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.

Upvotes: 1

Related Questions