I just want to set certain JButton
as the default button (i.e. when pressing ENTER
, it executes its action). Following this answer and few others, I tried them all:
SwingUtilities.windowForComponent(this)
SwingUtilities.getWindowAncestor(this)
someJPanelObj.getParent()
SwingUtilities.getRootPane(someJButtonObj)
But they all return null...
Here is the code:
public class HierarchyTest {
@Test
public void test(){
JFrame frame = new JFrame();
frame.add(new CommonPanel());
}
}
CommonPanel:
class CommonPanel extends JPanel {
CommonPanel() {
JButton btn = new JButton();
add(btn);
Window win = SwingUtilities.windowForComponent(this); // null :-(
Window windowAncestor = SwingUtilities.getWindowAncestor(this); // null :-(
Container parent = getParent(); // null :-(
JRootPane rootPane = SwingUtilities.getRootPane(btn); // null :-(
rootPane.setDefaultButton(btn); // obvious NullPointerException...
}
}