正如標題所說,我正試圖向JPanel添加一個keylistener。到目前爲止,我得到它的唯一方法是添加一個空的文本框並單擊它。現在我不想在我的JPanel中有一個空的textfield,所以我想將keylistener添加到面板本身。JPanel中的KeyListener無法正常工作(面板集中)
這裏是一流的,我在談論:
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);
}
}
有誰知道如何使這項工作?
http://stackoverflow.com/questions/11487369/jpanel-doesnt-respone-to-keylistener-event。檢查這LINL – Raghunandan