Reputation: 124646
It seems that JButton
doesn't automatically receive the focus when clicked, unless I explicitly configured the button with .setRequestFocusEnabled(true)
. The application I'm working with has a lot of buttons created in many different places (i.e. not via a factory method), and I need all of them to request the focus when clicked.
Is there an easy way to change the default behavior so that buttons request the focus on click by default, for example by setting some property? Or I need to hunt 'em all down and call .setRequestFocusEnabled(true)
on each button one by one?
Upvotes: 2
Views: 855
Reputation: 20059
A JButton should get the focus when clicked. You have probably buttons that have been modified to not do that. However that doesn't solve yoir problem.
You could change your buttons after the entire UI has been created (assuming a GUI is not modified while open) - this way you only need one call site per frame/dialog:
public static class FocusHelper {
public static void alterButtons(Component container) {
if (component instanceof Container) {
Component[] children = ((Container) component).getComponents();
for (Component child : children) {
alterButtons(child);
}
} else if (component instanceof JButton) {
((JButton) component).setRequestFocusEnabled(true);
}
}
}
The helper method just scans the entire component hierarchy for buttons and calls setRequestFocusEnabled() for each JButton (you may want to check for other component type(s) like AbstractButton, depending on what you want to achieve). You would just call the method from wherever the GUI is created and pass the top level container (JFrame, JDialog or any other Container component).
Upvotes: 1
Reputation: 17839
maybe you can create a subclass that inherits from JButton and implement the functionality there:
public class MyJButton extends JButton {
public MyJButton(String string, Icon icon) {
super(string, icon);
this.setRequestFocusEnabled(true);
}
public MyJButton(Action action) {
super(action);
this.setRequestFocusEnabled(true);
}
public MyJButton(String string) {
super(string);
this.setRequestFocusEnabled(true);
}
public MyJButton(Icon icon) {
super(icon);
this.setRequestFocusEnabled(true);
}
public MyJButton() {
super();
this.setRequestFocusEnabled(true);
}
}
Now you have to replace all your JButtons with MyJButton Object
Upvotes: 0