我正在尝试使用KeyListener在JFrame中移动已创建的矩形(实际上,我正在更改已创建的X和Y变量)。我想声明我不希望使用键绑定。我想使用KeyListener。话虽如此,我似乎在这里找不到我的逻辑有什么问题。
框架(主)类:
import java.awt.Color;
import javax.swing.JFrame;
@SuppressWarnings ("serial")
public class GameFrame extends JFrame
{
public static void main (String[] args)
{
JFrame frame = new JFrame ("Java Game");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setSize (1000, 600);
frame.getContentPane().setBackground (Color.WHITE);
frame.getContentPane().add (new GamePaint());
frame.addKeyListener (new GameController());
frame.setVisible (true);
}
}
油漆类:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
@SuppressWarnings ("serial")
public class GamePaint extends JComponent
{
public int x;
public int y;
public void paintComponent (Graphics graphics)
{
super.paintComponent (graphics);
graphics.setColor (Color.BLACK);
graphics.fillRect (x, y, 100, 100);
}
}
控制器类:
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class GameController implements KeyListener
{
GamePaint paint = new GamePaint();
public void keyPressed (KeyEvent event)
{
if (event.getKeyCode() == KeyEvent.VK_LEFT)
{
paint.x--;
paint.repaint();
}
else if (event.getKeyCode() == KeyEvent.VK_RIGHT)
{
paint.x++;
paint.repaint();
}
}
public void keyReleased (KeyEvent event) {}
public void keyTyped (KeyEvent event) {}
}
最佳答案
您正在创建GamePaint
的多个实例...
frame.getContentPane().add (new GamePaint());
和
public class GameController implements KeyListener
{
GamePaint paint = new GamePaint();
因此,当您
GameController
控制器尝试更改矩形的x
/ y
位置时,它不会与实际上在屏幕上的GamePaint
实例交互。而是创建一个
GamePaint
实例,将其添加到框架中,然后将引用传递给GameController
GamePaint gp = new GamePaint();
frame.getContentPane().add (gp);
frame.addKeyListener (new GameController(gp));
并更新
GameController
...public class GameController implements KeyListener
{
private GamePaint paint;
public GameController(GamePaint paint) {
this.paint = paint;
但是这种方法很奇怪...不是
GamePaint
应该接收键盘输入而不是框架输入吗?相反,可以考虑使用键绑定API,它可以解决与
KeyListener
相关的许多其他问题。有关更多详细信息,请参见How to Use Key Bindings代替控制器直接修改
x
/ y
属性,它应该以这种方式GamePaint
调用moveLeft
类上的方法(类似moveRight
,GamePaint
等)。可以做出决定意味着什么...但是,就我个人而言,我将在其中注入一个模型,该模型控制实体的位置,并且
GamePaint
只需绘制并由控制器控制...但这就是我...关于java - 如何使用KeyListener在JFrame中移动矩形?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28357334/