简体   繁体   English

JTextField除非单击,否则不会获得焦点

[英]JTextField to not gain focus unless clicked

I have a JTextField that is defined as follows: 我有一个JTextField定义如下:

JTextField chatTextField = new JTextField();
chatTextField.setRequestFocusEnabled(false);
chatTextField.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent arg0) {
        chatTextField.requestFocusInWindow();
    }
});
chatTextField.setFocusTraversalKeysEnabled(false);
chatTextField.setVisible(true);

There are some other method calls I have removed for simplicity purposes. 为了简单起见,我还删除了其他一些方法调用。

My chatTextField lives in a JPanel that is added to 'theDesktop'. 我的chatTextField驻留在添加到“ theDesktop”中的JPanel中。

JFrame frame = new JFrame("Test");
JLayeredPane theDesktop = new JDesktopPane();
frame.getContentPane().add(theDesktop);
frame.setFocusable(true);

I have many other JPanels that are also added to 'theDesktop' that represent other windows (backpack, bank, etc.). 我还有许多其他的JPanels也添加到了'theDesktop'中,它们代表其他窗口(背包,银行等)。 I only want chatTextField to gain focus when I click the mouse into it (or when I press enter which I also have wired up via an action). 我只希望chatTextField在单击鼠标时获得焦点(或者当我按Enter时也已通过操作将其连接起来)。

Sometimes it is getting focus, when closing other windows, and driving me insane. 有时,当关闭其他窗户并使我发疯时,它会变得聚焦。 You are unable to close the chat panel or the button panel. 您无法关闭聊天面板或按钮面板。 Can anyone see anything that is wrong? 谁能看到任何不对的地方? I am having trouble coming up with SSCCE because my gui stuff is huge and this is a networked game. 我在使用SSCCE时遇到了麻烦,因为我的GUI东西很大,而且这是一个网络游戏。 Any help would be greatly appreciated. 任何帮助将不胜感激。

Here is how I solved this. 这是我解决此问题的方法。 Kinda hacky, but it works I suppose. Kinda hacky,但是我想它可以工作。

Anytime the focus was transferred to the chat text box (ie, closing a certain window) I switched the focus to my button bar (always visible): 每当焦点转移到聊天文本框(即关闭某个窗口)时,我便将焦点切换到按钮栏(始终可见):

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        MyClient.buttonBarFrame.requestFocusInWindow(); //so chat does not request focus
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM