Reputation: 3244
I've been struggling with this for way too long. When I'm done typing in a jTextField, I want it to lose focus when I click on the window outside the textfield. I can't figure out how to do this. The best I can to is transfer focus to the next textfield.
Upvotes: 6
Views: 10214
Reputation: 324207
Why do you want to lose focus? I'm sure there is better design then to force the user to click on the window to cause the text field to lose focus.
Anyway, the text field will lose focus when another component gains focus. By default a panel is not focusable so clicking on it will not cause the text field to lose focus. Make the panel focusable:
panel.setFocusable( true );
Of course now when the user uses the tab key, the panel will now be included in the tab order. Thats another reason this seems like a bad design.
Upvotes: 2
Reputation: 12369
Consider your class extends JFrame:
JTextField jTextField1 = new JTextField();
addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTextField1.setFocusable(false);
}
});
Hope this help...
Upvotes: 0