如何使用KeyListener在JFrame中移动矩形?

时间:2015-02-06 01:53:52

标签: java swing jframe keylistener

我正在尝试使用KeyListener在JFrame中移动我创建的矩形(实际上,我正在更改我创建的X和Y变量)。我想声明我希望使用键绑定。我想使用KeyListener。话虽如此,我似乎无法在这里找到任何错误。

Frame(Main)类:

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);
    }
}

Paint类:

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) {}
}

1 个答案:

答案 0 :(得分:2)

您正在创建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,{{1等等......),这种方式moveRight可以做出关于这意味着什么的决定......

但是,就个人而言,我在那里注入了一个模型,它控制了实体的位置,而GamePaint只是简单地绘制了,而控制器控制了...但那就是我......