Swing make a JButton not focussable
I want to make a Java swing button 'not-focussable开发者_如何转开发'. The button should not receive focus at all, but should be able to receive mouse clicks.
I thought the following options, but these either dont solve my problem completely, or dont seem elegant. Are there any other/better/suggested options?
- Move the focus to the next component immediately when the button receives focus (but then what do I do if the button is the only component on the UI other than labels?)
- Implement another non-focusable component as a button (a label with mouse events, borders...) (this does not look very elegant to me)
- Create a anonymous button implementation that overides the keyboard events so that it does not respond to keyboard events (this does not solve the focus problem, but is somwhat ok for me, since the root of the problem is to avoid accidental keyboard clicks. I will do this only if there are no options at all, but even then prefer option 2)
All Swing components have a setFocusable method to do this:
JButton button = ...
button.setFocusable(false);
Did you try to call the setFocusable()
method inherited from java.awt.Component
?
Resources :
- Javadoc - Component.isFocusable()
- Oracle.com - Focus tutorial
You can implement your own FocusTraversalPolicy (or extend e.g. ContainerOrderFocusTraversalPolicy) with an accept method that just doesn't like your button.
JFrame frame = new JFrame();
... /* create other components */
frame.setFocusTraversalPolicy(new ContainerOrderFocusTraversalPolicy() {
public boolean accept(Component c) {
return super.accept(c) && c!=iDontLikeYouButton;
}
});
精彩评论