我正在研究一个非常简单的 Java 项目,试图了解如何使用 KeyListener。我创建了一个 Main 类和一个 KeyListener、MouseListener 类。当我按下键盘键时,我想发生一些事情。到目前为止,当我单击时,唯一有效的是“你好”。
这是我的代码:
import javax.swing.JFrame;
import javax.swing.JPanel;
public class KeyPractice{
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.addKeyListener(new KeyEar());
panel.addMouseListener(new KeyEar());
frame.add(panel);
frame.setVisible(true);
frame.setSize(400, 400);
}
}
和 Keylistener 类....
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class KeyEar implements KeyListener, MouseListener {
public KeyEar(){
}
@Override
public void mouseClicked(MouseEvent arg0) {
System.out.println("Hello");
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent arg0) {
System.out.println("Hello");
}
@Override
public void keyReleased(KeyEvent arg0) {
System.out.println("Hello");
}
@Override
public void keyTyped(KeyEvent arg0) {
System.out.println("Hello");
}
}