KeyListener不会做任何事情

时间:2015-12-01 00:45:13

标签: java swing jframe keylistener

我正在尝试向JFrame添加一个keylistener,但每当我点击一个按钮时,都没有任何反应。我试图让keylistener只打印一些基本的东西,但每当我尝试使用if语句时,控制台中没有任何反应。

package gui;

import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.JButton;

public class KeyListener implements java.awt.event.KeyListener {

ArrayList <JButton> _buttons;
JFrame _frame1;

public KeyListener(ArrayList <JButton> buttons, JFrame frame1){
    _buttons = buttons;
    _frame1 = frame1;
    _frame1.addKeyListener(this);
    _frame1.requestFocusInWindow();
    _frame1.setFocusable(true);
    this.keyTyped();
}

@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub
    if (e.getKeyCode() == KeyEvent.VK_LEFT){

        System.out.println("yes");
    }
}

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

}

@Override
public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub

}

}

这是我的keylistener类

这是我的游戏类

package model;

import java.awt.event.KeyListener;

import javax.swing.*;

public class Game implements Runnable{

KeyListener _keylistener;

@Override
public void run() {
    JFrame frame1 = new JFrame("KeyBricks");
    frame1.setVisible(true);

    JPanel panel1 = new JPanel();


    frame1.addKeyListener(_keylistener);
    model.Board board = new model.Board(panel1);

    frame1.add(panel1);

    frame1.pack();

    frame1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);


}

}

1 个答案:

答案 0 :(得分:0)

您可以注册KeyEventDispatcher

@Entity
public class Entity {

  @Id
  private Long id;

  @ManyToOne( fetch = FetchType.LAZY )
  @JoinColumn( name = "product_id" )
  private Product product;     

  @Enumerated(EnumType.STRING)
  private Enum enum;

请注意,已注册的KeyEventDispatcher将在之前接收KeyEvents ,并将其分派到目标,允许重新定位事件,使用它,分发事件本身或进行其他更改。