java转义出基于文本字段的搜索栏
我有一个带有搜索栏的菜单栏,它是用JTextField
实现的,如下所示:
public class Ui_Frame {
private static JFrame f;
private static DrawPanel drawPanel;
public static void main(String[] args) {
SwingUtilities.invokeLater(Ui_Frame::createAndShowGUI);
}
private static void createAndShowGUI() {
f = new JFrame("Frame");
drawPanel = new DrawPanel(); //A class that extends JPanel where I draw
JMenuBar menubar = new JMenuBar();
JMenu j_menu_data = new JMenu("Data");
JTextField j_menu_searchfield = new JTextField();
j_menu_searchfield.setSize(new Dimension(100,20));
menubar.add(j_menu_data);
menubar.add(j_menu_searchfield);
f.setJMenuBar(menubar);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(drawPanel);
f.pack();
f.setVisible(true);
}
}
我有KeyListener
个DrawPanel
类的KeyListener
个,这些工作很好。问题是,当我如上所述将搜索栏JTextField
添加到菜单栏时,我写入的所有内容都会写入文本字段,并且我的键侦听器不会触发。我无法“走出”文本字段,因此,如果我在绘图区域内单击,我按下的所有键仍会放入文本字段
我试过getFocus()
找DrawPanel
但是没有用
如何解决这个问题
编辑: DrawPanel类,因此您拥有运行它所需的所有类:
public class DrawPanel extends JPanel {
public DrawPanel() {
addKeyListener(new CustomKeyListener());
this.setBackground(new Color(220,220,220));
setBorder(BorderFactory.createLineBorder(Color.black));
setFocusable(true);
setVisible(true);
}
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
protected void paintComponent(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
super.paintComponent(g2D);
}
class CustomKeyListener implements KeyListener {
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_SPACE) {
System.out.println("Pressed SPACE");
}
}
@Override
public void keyPressed(KeyEvent e) { }
@Override
public void keyReleased(KeyEvent e) { }
}
}
# 1 楼答案
启动Swing应用程序时,
JTextField
最初具有键盘焦点。您之所以知道这一点,是因为您看到光标在JTextField
内闪烁用鼠标单击
DrawPanel
不会将键盘焦点转移到DrawPanel
。您知道这一点,因为在DrawPanel
内单击鼠标后,光标仍在JTextField
内闪烁您可以通过点击键盘上的TAB键将键盘焦点从
JTextField
转移到DrawPanel
,因为这是默认的焦点遍历键。您知道JTextField
不再具有键盘焦点,因为其中没有闪烁的光标如果您真的希望
DrawPanel
通过单击其中的鼠标来获得键盘焦点,您可以将MouseListener
添加到DrawPanel
,如下面的代码所示,该代码本质上是您添加了MouseListener
的代码(对于类DrawPanel
)请注意,我没有更改类
Ui_Frame
请注意,如果方法
requestFocusInWindow()
成功,它将返回true