我有一個JPanel使用KeyListener作爲窗口的內容窗格;但是,在JPanel頂部的網格佈局中有按鈕和文本字段。給予JPanel優先級重點
如何優先處理編輯文本或單擊按鈕後保留焦點的JPanel的焦點,以便我可以讀取鍵輸入?
我有一個JPanel使用KeyListener作爲窗口的內容窗格;但是,在JPanel頂部的網格佈局中有按鈕和文本字段。給予JPanel優先級重點
如何優先處理編輯文本或單擊按鈕後保留焦點的JPanel的焦點,以便我可以讀取鍵輸入?
您只需在focusLost
事件上添加FocusListener
,然後再請求焦點。事情是這樣的:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JPanelFocus {
public static void main(String... argv) throws Exception {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("FocusTest");
JButton b = new JButton("Button");
final JPanel p = new JPanel();
p.add(b);
// Here is the KeyListener installed on our JPanel
p.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent ev) {
System.out.println(ev.getKeyChar());
}
});
// This is the bit that does the magic - make sure
// that our JPanel is always focussed
p.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent ev) {
p.requestFocus();
}
});
f.getContentPane().add(p);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
// Make sure JPanel starts with the focus
p.requestFocus();
}
});
}
}
,如果你有需要保持專注,但(你提到一個可編輯的文本字段)字段這將無法正常工作。關鍵事件應該何時進入文本字段以及何時應該進入JPanel?
作爲一種替代方法,您也可以使子組件不可聚焦。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyPanel extends JPanel implements KeyListener {
public MyPanel() {
this.setFocusable(true);
this.addKeyListener(this);
// for each component
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addItem("Item1");
this.add(comboBox);
// this is what keeps each child from intercepting KeyEvents
comboBox.setFocusable(false);
}
public void keyPressed(KeyEvent e) { ... }
public void keyTyped(KeyEvent e) { ... }
public void keyReleased(KeyEvent e) { ... }
public static void main(String[] args) {
// create a frame
JFrame frame = new JFrame();
frame.setSize(640, 480);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add MyPanel to frame
MyPanel panel = new MyPanel();
frame.add(panel);
frame.setVisible(true);
}
}