kralco626
kralco626

Reputation: 8644

java, swing, awt, remove focus from all objects

I'm doing this project for school and for some reason one of by Buttons in one of my Panels has focus(i can change it with the tab button) Well whatever button has the focus is acting weird.

Is there a way that I can have no button have focus? ie. have nothing selected by the tab button?

notice the Rectangle button has a dotted line around it. I want to make that go away.

Thanks! alt text

Upvotes: 8

Views: 12868

Answers (5)

algonell
algonell

Reputation: 175

Another option is to focus on the frame:

frame.requestFocus();

This will allow keyboard focus via Tab if necessary.

Upvotes: 0

Yogesh G
Yogesh G

Reputation: 1160

public void removeFocusFromAllObjects(Container container) {
    container.setFocusable(false);
    for (Component child : container.getComponents()) {
        if (child instanceof Container) {
            removeFocusFromAllObjects((Container) child);
        } else {
            child.setFocusable(false);
        }
    }
}

I have written above code to remove focus from all the components recursively inside a parent component. Hope it might be useful to someone visiting this post.

Upvotes: 0

Alexandre de Champeaux
Alexandre de Champeaux

Reputation: 1892

If you don't want anything to get focus, you can use:

button.getRootPane().requestFocus();

Using setFocusable is going to move focus to the next focusable component.

Upvotes: 3

brimborium
brimborium

Reputation: 9512

If you just want it to not show the dotted line, you can also use

button.setFocusPainted(false);

The button will still be focusable, but you won't see the dotted line.

Upvotes: 7

camickr
camickr

Reputation: 324147

button.setFocusable(false);

Upvotes: 15

Related Questions