我希望我的頂級JFrame以及JDesktopPane能夠隨時監聽關鍵事件,無論當前哪個組件是關注/可見的。JFrame/JDesktop沒有獲得重點關注
目前,當這個程序啓動時,JFrame正在收到關鍵事件確定。但是,如果單擊JinternalFrame,則事件不再會到達JFrame。即使我點擊了JInternalFrame(應該是JDesktop組件)之外的地方,事件也不會像開始時那樣到達JFrame。爲什麼?謝謝。
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class focus extends JFrame implements KeyListener {
private focus() {
JDesktopPane desktop = new JDesktopPane();
setContentPane(desktop);
addPane(this, "one");
addPane(this, "two");
addPane(this, "three");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(400, 450);
addKeyListener(this);
}
public static void main(String[] args) {
focus t = new focus();
}
private void addPane(JFrame frame, String name) {
JTextArea textArea = new JTextArea();
textArea.setName(name);
textArea.setEditable(false);
addWindow(frame, textArea, name);
}
private JInternalFrame addWindow(JFrame frame, JComponent component,
String name) {
JScrollPane scrollablePane = new JScrollPane(component);
JInternalFrame iframe = new JInternalFrame(name + " ", true, true,
true, true);
iframe.setSize(300, 300);
iframe.setLocation((int) (100 * Math.random()),
(int) (100 * Math.random()));
iframe.setVisible(true);
iframe.getContentPane().add(scrollablePane);
frame.getContentPane().add(iframe);
return iframe;
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
System.err.println(e.getKeyChar());
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}