按下UP键时,乒乓球拍底部不会向上移动 [英] Pong Paddle bottom doesn't move up when UP key is pressed

查看:90
本文介绍了按下UP键时,乒乓球拍底部不会向上移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个乒乓球游戏,但由于某种原因,我的乒乓球拍无法正确移动.

I'm trying to make a pong game but my pong paddle isn't moving up properly for some reason.

当我按下DOWN箭头键时,它会向下移动.但是,当我按下UP箭头键时,整个拨片的长度会更长……如果我调整窗口的大小,则拨片将恢复到该位置的正常长度.如果我按UP键,它将再次继续向上延伸.

When I hit the DOWN arrow key it moves down just fine. But when I hit the UP arrow key the whole paddle just get's longer upwards... If i resize the window the paddle returns to it's normal length at that position. If i press UP key it again continues to extend upwards.

我不认为这是我的代码逻辑,而是有关清除先前绘制的桨的一些信息……这是我的代码,

I don't think its my code logic but something about clearing the previously drawn paddle... here's my code,

桨的代码:

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.geom.Rectangle2D;

import javax.swing.JPanel;

public class Paddle extends JPanel {

    int x;
    int y;
    int width;
    int height;

    Paddle(){
        this.x = 0;
        this.y = 0;
        this.height = 40;
        this.width = 10;
    }

    Paddle(int x, int y, int width, int height){
        this.x = x;
        this.y = y;
        this.height = height;
        this.width = width;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.BLACK);
        g.fillRect(x, y, width, height);
    }

    public void moveDown(){
        this.y += 3;
        repaint();
        System.out.println("h: " + height + " x: " + x + " y: " + y + " getW: " + getWidth() + " getH: " + getHeight());
    }

    public void moveUp(){
        this.y -= 3;
        repaint();
        System.out.println("h: " + height + " x: " + x + " y: " + y + " getW: " + getWidth() + " getH: " + getHeight());
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

}

完整游戏代码:

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Pong extends JFrame {

    Pong() {
        final Paddle p1Paddle = new Paddle();

        Paddle p2Paddle = new Paddle();
        p1Paddle.addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {
                // TODO Auto-generated method stub
                //super.keyPressed(arg0);

                switch (e.getKeyCode()) {
                    case KeyEvent.VK_DOWN:
                        p1Paddle.moveDown();
                        break;
                    case KeyEvent.VK_UP:
                        p1Paddle.moveUp();
                        break;
                    default:
                        System.out.println("please press up or down");
                }

            }
        });

        setLayout(new BorderLayout());
        add(p1Paddle, BorderLayout.CENTER);

        //only focused components can recieve key events...
        p1Paddle.setFocusable(true);
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JFrame frame = new Pong();
        frame.setTitle("Pong");
        frame.setSize(650, 300);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

}

在此问题上的任何帮助或常规代码建议,将不胜感激.

Any help on this issue or general code advice would be appreciated.

推荐答案

从代码片段很难看出来,但是KeyListeners并不是很可靠.如果击键被消耗(通过UI和基础实现),则可能不会通知您.

A little hard to tell from the code snippet, but, KeyListeners aren't very reliable. If the key stroke is been consumed (by the UI and underlying implementation) you may not be notified.

尝试查看InputMap和ActionMap.

Try looking at InputMap and ActionMap instead.

InputMap im = getInputMap(JTable.WHEN_FOCUSED_COMPONENT);
ActionMap am = getActionMap();

KeyStroke downKey = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
KeyStroke upKey = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);

im.put(downKey, "Action.down");
im.put(upKey, "Action.up");

am.put("Action.down", new DownAction());
am.put("Action.up", new UpAction());

看看带你去哪里...

And see where it takes you...

更新:嗯,这非常明显,您已经覆盖了面板的x/y width/height方法,希望布局管理器使用它们来布局组件,但实际上并没有提供知道如何处理组件的布局管理器.

Update: Ahh, it's so obvious now, you've overridden the x/y width/height methods of the panel expecting the layout manager to use them to layout out the component, but not really providing a layout manager who knows how to deal with it.

BorderLayout不在乎您的大小"或位置"要求,它将以您认为的组件应该覆盖的范围覆盖它们.

BorderLayout does not care about you "size" or "position" requirements, it will override them with what it thinks you component should be.

您要做的是改用绝对布局管理器(空).另外,您也不想实施X/Y,宽度/高度管理,因为这已经为您解决了.

What you want to do is use an absolute layout manager instead (null). Also, you DON'T want to implement the X/Y, width/height management, as this is already taken care for you.

所以

在乒乓球课上.将布局管理器从BorderLayout更改为null(还更新add(paddle)方法以删除BorderLayout引用,不是必需的,但可以消除混乱).

In the Pong class. Change the layout manager from BorderLayout to null (also update the add(paddle) method to remove the BorderLayout reference, not required, but removes confusion).

在Paddle类中,删除对x/y,宽度/高度的所有引用,您不需要它们.而是使用setBounds/setLocation.

In the Paddle class, remove all references to the x/y, width/height, you don't need them. Instead use setBounds/setLocation.

public class Paddle extends JPanel {

Paddle(){

        this(0, 0, 20, 40);

}

Paddle(int x, int y, int width, int height){

        setBounds(x, y, width, height);

}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLACK);
    // The graphics context has already been translated to x/y for use,
    // so we don't need to care about it
    g.fillRect(0, 0, getWidth(), getHeight());
}

public void moveDown(){

        setLocation(getX(), getY() + 3);

}

public void moveUp(){

        setLocation(getX(), getY() - 3);

}

}

中提琴也可以.

这篇关于按下UP键时,乒乓球拍底部不会向上移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆