KeyListener不更改JPanel

时间:2014-03-27 19:25:30

标签: java swing jpanel keylistener

所以我创建了一个JPanel的扩展版本,不幸的是它没有响应任何键输入。你能告诉我这是什么问题吗?我搜索了所有其他帖子,但我找不到我的错误。

public class MyPanel extends JPanel implements ActionListener,KeyListener{

Timer tm=new Timer(5,this);
int x=0,y=0 ,velX=0, velY=0;

public MyPanel(){
    tm.start();
    addKeyListener(this);
    setFocusable(true);
    requestFocusInWindow();
}

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

    g.fillRect(0,0,this.getWidth(),this.getHeight());
     g.setColor(Color.RED);
    g.fillRect(x,30,50,30);



}

public void actionPerformed(ActionEvent e){

    if(x<0||x>370)
    velX=-velX;

    if(y<0||y>370)
    velY=-velY;

    y=y+velY;
    x=x+velX;
    repaint();
}

public void keyPressed(KeyEvent e){
    int c=e.getKeyCode();
    System.out.println("Cascsadas");
    if(c==KeyEvent.VK_LEFT){
        velX=-1;
        velY=0;
    }

    if(c==KeyEvent.VK_UP){
        velX=0;
        velY=-1;
    }

     if(c==KeyEvent.VK_RIGHT){
        velX=1;
        velY=0;
    }

    if(c==KeyEvent.VK_DOWN){
        velX=0;
        velY=1;
    }

}

public void keyTyped(KeyEvent e){};
public void keyReleased(KeyEvent e){};



}

我使用这个JPanel的课程是:

public class Tester
{
   public static void main(String[] args){

    MyPanel t=new MyPanel();
    JFrame jf=new JFrame();
    jf.setTitle("Tutorial");
    jf.setVisible(true);
    jf.setSize(600,400);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.getContentPane().add(t,BorderLayout.CENTER);

}
}

2 个答案:

答案 0 :(得分:2)

您的代码无效,因为您的面板没有焦点。

requestFocusInWindow()方法仅在GUI上显示面板可见时才有效。在构造函数中调用该方法没有任何效果(并且不需要)。

然而,真正的问题是在框架可见后将面板添加到框架。你的代码应该是这样的:

jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.getContentPane().add(t,BorderLayout.CENTER);
jf.setSize(600,400);
jf.setVisible(true);

关键是在框架可见之前将面板添加到内容窗格。使框架可见然后改变其大小也没有意义,因此我总是将框架视为最后一个声明。

  

我搜索了所有其他帖子,但我找不到我的错误

我觉得很难相信。每天都会询问此问题,我们始终建议您使用Key Bindings,那么为什么还要尝试使用KeyListener?

Swing旨在与Key Bindings一起使用。有关更多信息和使用密钥绑定的方法,请参阅Motion Using the Keyboard

答案 1 :(得分:1)

我已在此处的相同背景中发布了答案

Diagonal movement of a simple sprite (up-down-left-right movement already done)

这篇关于KeyListener的帖子将帮助您更多地了解它。


以下是要启动的示例代码:

(向左,向右,向上,向下和对角方向移动)

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 java.util.Set;
import java.util.TreeSet;

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

public class Apple extends JPanel implements ActionListener, KeyListener {

    Timer timer = new Timer(5, this); // this refers to actionListener
    int x = 0, velx = 0;
    int y = 0, vely = 0;

    public Apple() {
        timer.start();
        addKeyListener(this); // this refers to keylistener
        setFocusable(true);
        setFocusTraversalKeysEnabled(false); // because we are not using the shift or ctrl key
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        // outer rectangle
        g.setColor(Color.BLUE);
        g.fillRect(x, y, 50, 50);
    }

    public static void main(String[] args) {
        Apple apple = new Apple();
        apple.setSize(500, 500);
        JFrame frame = new JFrame();
        frame.add(apple);
        frame.setLayout(null);
        frame.setTitle("The Game");
        frame.setSize(500, 500);
        frame.setVisible(true);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    @Override
    // animates rectangle
    public void actionPerformed(ActionEvent arg0) {
        if (x < 0) {
            velx = 0;
            x = 0;
        }
        if (x > 450) {
            velx = 0;
            x = 450;
        }
        if (y < 0) {
            vely = 0;
            y = 0;
        }
        if (y > 450) {
            vely = 0;
            y = 450;
        }

        x = x + velx;
        y = y + vely;
        repaint();
    }

    // Set of currently pressed keys
    private final Set<Integer> pressed = new TreeSet<Integer>();

    @Override
    public void keyPressed(KeyEvent arg0) {
        System.out.println(KeyEvent.VK_LEFT + "-" + KeyEvent.VK_RIGHT + "-" + KeyEvent.VK_UP + "-"
                + KeyEvent.VK_DOWN);
        int c = arg0.getKeyCode();
        pressed.add(c);
        if (pressed.size() > 1) {
            Integer[] array = pressed.toArray(new Integer[] {});
            if (array[0] == KeyEvent.VK_LEFT && array[1] == KeyEvent.VK_UP) {
                velx = -4;
                vely = -4;
            } else if (array[0] == KeyEvent.VK_UP && array[1] == KeyEvent.VK_RIGHT) {
                velx = 4;
                vely = 4;
            } else if (array[0] == KeyEvent.VK_RIGHT && array[1] == KeyEvent.VK_DOWN) {
                velx = 4;
                vely = -4;
            } else if (array[0] == KeyEvent.VK_LEFT && array[1] == KeyEvent.VK_DOWN) {
                velx = -4;
                vely = 4;
            }
        } else {
            if (c == KeyEvent.VK_LEFT) {
                velx = -4;
                vely = 0;
            } else if (c == KeyEvent.VK_RIGHT) {
                velx = 4;
                vely = 0;
            } else if (c == KeyEvent.VK_UP) {
                velx = 0;
                vely = -4;
            } else if (c == KeyEvent.VK_DOWN) {
                velx = 0;
                vely = 4;
            }
        }

    }

    @Override
    public void keyReleased(KeyEvent arg0) {
        velx = 0;
        vely = 0;

        pressed.remove(Integer.valueOf(arg0.getKeyCode()));
    }

    @Override
    public void keyTyped(KeyEvent arg0) {

    }
}