Hello everyone on daniweb!:) I'm trying to make a programme which will move a picture to the sides when pressing the right or left arrowkeys. I did successfully put a picture in and I was able to change the side coordinates(called "side" in the programme) to make the picture move. However now I want it to be done with KeyListener. I have been trying to browse the internet for help but I havnt yet found anything which worked. One problem is that I dont know what to add the keylistener to(now its added to "img" because I dont know better). Does anybody know how I can make this work? I'll be so thankfull for your help!:)

Here is the code:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Background3
{
  public static void main(String[] skit)
  {
    ImagePanel panel = new ImagePanel(new ImageIcon("Projektbilder/Bakgrund.png").getImage());
    JFrame frame = new JFrame();
    frame.getContentPane().add(panel);
    frame.setSize(500,500);
    frame.setVisible(true);

  }
}

class ImagePanel extends JPanel
{
  private int side=0;

  private Image img;

  public ImagePanel(String img)
  {
    this(new ImageIcon(img).getImage());
  }

  public ImagePanel(Image img)
  {
    this.img = img;
    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
    setPreferredSize(size);
    setMinimumSize(size);
    setMaximumSize(size);
    setSize(size);
    setLayout(null);
  }

  img.addKeyListener(this);

  public void keyTyped(KeyEvent e)
  {
  	if(e.getKeyCode() == e.VK_RIGHT)
  	{
  			side++;
  			repaint();
  	}

  	else if (e.getKeyCode() == e.VK_LEFT)
  	{
  			side--;
  			repaint();
  	}
  }

  public void keyPressed(KeyEvent e)
  {
  }

  public void keyReleased(KeyEvent e)
  {
  }


  public void paintComponent(Graphics g)
  {
    g.drawImage(img, side, 0, null);
  }

}

The listener would be added your panel. You could also use KeyBindings: http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html

Thank you so much for your quick reply:)! I have been trying to add the listener to "panel", "super" and all sorts I can think of to be honest. But I will start looking in to KeyBindings, as it might be better for this code.

Key listeners are very touchy about component focus. You have to be sure that your panel is focusable and actually receives the focus. You can call panel.requestFocusInWindow() after you have made the frame visible.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.