How to create a subclass of JButton that makes itself the window’s default button?
I understand that designating a default button is set on the JRootPane rather than the button itself. Instead of adding such code to each window, I would like to specify the default button by instantiating a subclass of JButton, “JButton_Default”. The subclass should locate the JRootPane and set itself to be the default button.
I tried doing this in the subclass’ constructor. Unfortunately, this approach works. I suppose that makes sense, as the button under construction is not yet an a form, so it cannot locate the JRootPane.
Is there some other way to program this JButton subclass?
Here’s my subclass that fails:
import javax.swing.*;
public class JButton_Default extends JButton {
public JButton_Default() {
super();
JRootPane pane = this.getRootPane();
pane.setDefaultButton(this);
}
}
SOLVED —————-
Here’s the code for a JButton subsclass that makes itself the default button of the window to which it has been added.
import javax.swing.*;
public class JButton_Default extends JButton {
@Override
public void addNotify() { // Upon being added to a window, make this JButton the default button of the window.
super.addNotify();
SwingUtilities.getRootPane( this ).setDefaultButton( this );
}
}
Override the addNotify() method of your JButton class. I believe this method gets invoked when the component is added to a frame. Or if this doesn’t work then add an AncestorListener to the button and listen for the ancestorAdded event.
Now you know the component is added to a top level container so you can get the root pane and set the button as the default.