为什么Key Listener有时只能工作

时间:2018-03-30 07:31:31

标签: java actionlistener keylistener

所以这是我的代码。我实现了keyListener和actionListener。我能够改变面板的坐标,因此它可以向左或向右移动。但我注意到keyListener没有很好地集中注意力。我必须一次又一次地关闭并重新运行应用程序以使其工作,我能够控制它。我听说过keyBidings,但我并没有真正得到它。如何实现keyBinding以使键盘响应更具可调性?

 package brickBreaker;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.Timer;

import javax.swing.JPanel;

public class game extends JPanel implements KeyListener, ActionListener {
    private Timer timer;
    private boolean play = false;
    private int playerx = 650;
    private int ballx=900, bally=500,ballxdir=-1,ballydir=-2;
    int delay =8;
    public game() {
        addKeyListener(this);
        setFocusable(true);
        setFocusTraversalKeysEnabled(false);
        timer = new Timer(delay, this);
        timer.start();

    }


    public void paint(Graphics g) {
        g.setColor(Color.BLACK);
        g.fillRect(1, 1, 1500 ,950);

        // user panel
        g.setColor(Color.CYAN);
        g.fillRect(playerx, 900, 250, 15);

        //ball
        g.setColor(Color.GREEN);
        g.fillOval(ballx, bally, 30, 30);

        g.dispose();
    }



    public void right() {
        play = true;
        playerx += 20;
    }
    public void left() {
        play = true;
        playerx -=20;
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        if(key ==KeyEvent.VK_LEFT) {
            System.out.print("Left\n");
            left();
        }if (key == KeyEvent.VK_RIGHT) {
            System.out.print("Right\n");
            right();
        }



    }

    @Override
    public void keyReleased(KeyEvent arg0) {


    }

    @Override
    public void keyTyped(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        timer.start();
        if (play) {

            ballx +=ballxdir;
            bally +=ballydir;
            if (ballx <0) {
                ballxdir =-ballxdir;
            }
            if (bally <0) {
                ballydir =-ballydir;
            }
            if (ballx <1000) {
                ballxdir =-ballxdir;
            }




        }
        repaint();

    }

}

1 个答案:

答案 0 :(得分:0)

很抱歉非常来回答,但我想我已经解决了你的问题。

你是对的 - 你需要在它工作之前反复打开和关闭JPanel。但问题在于:JPanel一直在失去焦点。所以你要做的就是添加:

requestFocus(true);

paint()方法,如下:

public void paint(Graphics g) {
    requestFocus(true);
    g.setColor(Color.BLACK);
    g.fillRect(1, 1, 1500 ,950);

    // user panel
    g.setColor(Color.CYAN);
    g.fillRect(playerx, 900, 250, 15);

    //ball
    g.setColor(Color.GREEN);
    g.fillOval(ballx, bally, 30, 30);

    g.dispose();
}

并且该程序有效!