3

What I'm trying to do is practice some swing coding. I created a rectangle from scratch and gave it an x and y position on the frame. What I've been trying to do is use a key listener to update the x variable to move it left and right.

Here I created a class which implements an Action Listener:

    public class Board extends JPanel implements ActionListener {

I added "x" and "y" variables:

int x, y;
int dx;
int HEIGHT, WIDTH;
private final int DELAY = 50;

Next are some additional functions:

    public Board() {

    setBackground(Color.BLACK);
    setFocusable(true);
    setDoubleBuffered(true);
    addKeyListener(new TAdapter());

    x = 15;
    y = 150;
    dx = 5;    //This is what I want to use to update the x variable if possible.

    HEIGHT = 15;
    WIDTH = 15;

}

This is where I created the square with said "x" and "y" variables:

public void paint(Graphics g) {
    super.paint(g);

    int red = 103;
    int green = 10;
    int blue = 100;
    Color square = new Color(red, green, blue);


    g.setColor(square);
    g.fillRect(x, y, WIDTH, HEIGHT);

    Toolkit.getDefaultToolkit().sync();
}

Ok, now onto what I'm trying to accomplish.

I created a "move" method that will be fed into the Action Performed method and then I created a Key Adapter method that handles the Key Events:

    public void move() {
        x += dx;
    }

    public void actionPerformed(ActionEvent e) {
    move();
    repaint();
}


private class TAdapter extends KeyAdapter {

    public void KeyPressed(KeyEvent e) {
        int key = e.getKeyCode();

        if (key == KeyEvent.VK_LEFT) {
            dx = 1;
        }

        if (key == KeyEvent.VK_RIGHT) {
            dx = -1;
        }
    }   
}

Here's a screenshot of what I'm getting:

black window with small purple square in the left side

Everything manifests through another class, but all that does is initialize the various JFrame components (size, visibility, etc.) and starts the program.

When I run the program I cannot get the x variable to update. Can someone let me know what I need to add?

Thanks.

4

1 回答 1

0

我认为你的问题是你的 actionPerformed 方法没有被调用,所以你的 move() 方法也没有被调用。您没有向任何内容添加 ActionListener,因此根本不会调用它。我会像这样在 keyPressed 中调用 move() 和 repaint()

if( key == KeyEvent.VK_LEFT ) {
    dx = 1;
    move();
    repaint();
}

if( key == KeyEvent.VK_RIGHT ) {
    dx = -1;
    move();
    repaint();
}

我很确定这会奏效。我还想指出您的代码中的两件事。首先,keyPressed 有一个小写的 k,而不是一个大写的。其次,你使用 dx 和按钮的方式,如果你按下左按钮,方块会向右移动;它会朝相反的方向发展。此外,就像 dann.dev 在他的评论中提到的那样,至少阅读那本书的第一章。它为您提供了有关视频游戏中的双缓冲、多线程的提示,并提供了一个可以使用的不错的循环。

于 2012-07-02T23:14:30.347 回答