正如标题所说,我正在尝试将 keylistener 添加到 JPanel。到目前为止,我让它工作的唯一方法是添加一个空的文本字段并单击它。现在我不想在我的 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);
}
}
有谁知道如何使这项工作?