Reputation: 4326
As the title says I'm trying to make add a keylistener to a JPanel. So far the only way I got it working was by adding an empty textfield and clicking on it. Now I don't want an empty textfield in my JPanel so I want to add the keylistener to the panel itself.
Here is the class I'm talking about:
package cookieClicker;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CookieView extends JPanel
{
private CookieModel cm;
private ImageIcon cookie;
public Rectangle rect;
public CookieView(CookieModel cm)
{
this.cm = cm;
this.setFocusable(true);
this.requestFocusInWindow();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
cookie = new ImageIcon("Untitled-1.png");
g.setColor(Color.ORANGE);
g.drawImage(cookie.getImage(), this.getWidth() / 2 - 100, this.getHeight() / 2 - 100, 200, 200, this);
rect = new Rectangle(this.getWidth() / 2 - 100, this.getHeight() / 2 - 100, 200, 200);
}
public void addListener(MouseListener m, KeyListener k)
{
this.addMouseListener(m);
this.addKeyListener(k);
}
}
Does anyone know how to make this work?
Upvotes: 0
Views: 6520
Reputation: 324118
panel is focused
How do you know the panel is focused?
The requestFocusInWindow()
method only works when the frame is already visible at the time the method is invoked. So invoking the method in your constructor won't do anything.
The basic code should be:
CookieView panel = new CookieView();
JFrame frame = new JFrame();
frame.add(panel);
frame.pack();
frame.setVisible(true);
panel.requestFocusInWindow();
Also you should make sure all the code is execute on the Event Dispatch Thread.
However, you should probably not even be using a KeyListener. In most cases Swing was designed to be used with Key Bindings. Read the tutorial to see if key bindings will work for you.
Finally, you should NOT be reading an Image file in the paintComponent() method. The painting methods are called whenever Swing determines a component needs to be repainted so it is inefficient to keep reading the image over and over.
Upvotes: 4