我有一段Java練習使用KeyListeners,我一直堅持使用它。任何幫助將不勝感激。練習是:在Java GUI中顯示在鼠標位置鍵入的字符
「編寫一個程序,從鍵盤獲取字符輸入並顯示鼠標指向的字符。」
我做了一些調試,看起來像KeyListener從不註冊時按下一個鍵。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class EventProgrammingExercise10 extends JFrame {
CharPanel chars;
private int x;
private int y;
String s;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
EventProgrammingExercise10 frame = new EventProgrammingExercise10();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public EventProgrammingExercise10() {
setTitle("EventProgrammingExercise10");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
chars = new CharPanel();
chars.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
chars.repaint();
}
});
add(chars);
}
public void setX(int n) {
x = n;
}
public void setY(int n) {
y = n;
}
class MouseLocListener extends MouseMotionAdapter {
public void mouseMoved(MouseEvent e) {
setX(e.getX());
setY(e.getY());
}
}
class CharPanel extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString(String.valueOf('a'), x, y);
}
}
}
謝謝。
感謝您的幫助。 –