KisnardOnline
KisnardOnline

Reputation: 740

JTextField to not gain focus unless clicked

I have a JTextField that is defined as follows:

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'.

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.). 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).

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. Any help would be greatly appreciated.

Upvotes: 0

Views: 142

Answers (1)

KisnardOnline
KisnardOnline

Reputation: 740

Here is how I solved this. Kinda hacky, but it works I suppose.

Anytime the focus was transferred to the chat text box (i.e., 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
    }
});

Upvotes: 1

Related Questions