how do I make a pictur move?.code:

public class picture extends JFrame{
    private static final long serialVersionUID = 1L;

    JLabel ball;
    int h = 100;
    int l = 200;

    public picture() {
        System.out.println("working");
        Icon bb = new ImageIcon(getClass().getResource("ball.jpg"));
        ball = new JLabel(bb);
            ball.setBounds(10, 10, h, l);
            ball.addKeyListener(new KeyListener() {
                public void keyTyped(KeyEvent e) {
                    e.consume();
                }

                public void keyReleased(KeyEvent e) {
                    add(ball);
                    e.consume();
                }

                public void keyPressed(KeyEvent e) {
                    int KeyCode = e.getKeyCode();
                    if (KeyCode == KeyEvent.VK_W) {
                        l++;
                    } else {
                        e.consume();
                    }

                }
            });
            add(ball);
    }

    public void positionSetter(int newh, int newl) {
        h = (newh >= 10 ? newh : 10);
        l = (newl >= 10 ? newl : 10);
        h = (newh >= 790 ? newh : 790);
        l = (newl >= 590 ? newl : 590);
    }
}

hello,
i see that your code is missing:
1) you need to add the main

public static void main(String [] arg)
{   new picture(); }

2) you added the key listener on the ball which is label, and i don't think it will work. so i advice you to add the key listener on the JFrame, so instead of "ball.addKeyListener" use "this.addKeyListener"

3)

 public void keyPressed(KeyEvent e) {
                    int KeyCode = e.getKeyCode();
                    if (KeyCode == KeyEvent.VK_W) {
                        l++;
                    } else {
                        e.consume();
                    }

when the key is pressed, you just increment l, and this will not move the picture, so you need to update its position.

l++;
positionSetter(h,l);
ball.setBounds(10, 10, h, l);

i hope this help.
regards

  • Swing/AWT doesn't know a new JComponent is added to already visible GUI, there isn't any notifier automatically relayout container, you have to call revalidate() and repaint() for animation/movement from keyboard

  • your consume() is quite contraproductive, to change this logics, add required numbers of JLabels to container, use proper LayoutManager, then just to play with JLabel.setIcon(my local variable)

Edited 2 Years Ago by mKorbel

That's a pathetic post. If you want some help you'll have to provide a LOT more info than that. Do you think we are all mind readers?

By the way, you need to take a look at positionSetter() method again... You are wrongly check for values...

This article has been dead for over six months. Start a new discussion instead.