views:

47

answers:

3

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?

  1. 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?)
  2. Implement another non-focusable component as a button (a label with mouse events, borders...) (this does not look very elegant to me)
  3. 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)
+2  A: 

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;
    }
});
ammoQ
Well, it's possibly overengineered... setFocusable should do the job, too. Feel free to downvote this ;-). Having worked on a setFocusTraversalPolicy problem yesterday, that was my first idea.
ammoQ
+1  A: 

Did you try to call the setFocusable() method inherited from java.awt.Component ?


Resources :

Colin Hebert
+2  A: 

All Swing components have a setFocusable method to do this:

JButton button = ...
button.setFocusable(false);
Steve McLeod
No idea how I missed this... looks like I already even *know* this...time for a coffee. Thanks anyway.
Nivas
It is easy to miss things in the Swing API - there are so many methods cluttering up the auto-complete, it is hard to find the one that may do what you want!
Steve McLeod