Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

java - Pong Paddle bottom doesn't move up when UP key is pressed

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

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,

Code for Paddle:

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

}

Code for Whole Game:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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...

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 does not care about you "size" or "position" requirements, it will override them with what it thinks you component should be.

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.

So.

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).

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

}

}

And viola, it works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...