尽管我将帧注册到 keyListener,但 keyListener 不会触发操作。在其他代码中,实现 KeyListener 接口、注册 JFrame 并覆盖适当的方法是 keyListener 工作所需的全部内容。
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Mains implements KeyListener {
private static Point point = new Point();
public Mains() {
final JFrame frame = new JFrame();
frame.setUndecorated(true);
JButton button = new JButton("Close Me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
frame.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
point.x = e.getX();
point.y = e.getY();
}
});
frame.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
Point p = frame.getLocation();
frame.setLocation(p.x + e.getX() - point.x, p.y + e.getY()
- point.y);
}
});
frame.setSize(300, 300);
frame.setLocation(200, 200);
frame.setLayout(new BorderLayout());
frame.getContentPane().add(button, BorderLayout.NORTH);
frame.getContentPane().add(new JLabel("Drag Me", JLabel.CENTER),
BorderLayout.CENTER);
frame.setVisible(true);
frame.addKeyListener(this);
}
public static void main(String[] args) {
new Mains();
}
public void keyPressed(KeyEvent e) {
System.out.println("pressed");
}
public void keyReleased(KeyEvent e) {
System.out.println("released");
}
public void keyTyped(KeyEvent e) {
}
}