我只想将某个JButton
设置为默认按钮(即按下ENTER
时,它会执行其操作)。在this answer和其他几个人之后,我尝试了所有这些:
SwingUtilities.windowForComponent(this)
SwingUtilities.getWindowAncestor(this)
someJPanelObj.getParent()
SwingUtilities.getRootPane(someJButtonObj)
但他们都归零......
以下是代码:
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...
}
}
答案 0 :(得分:3)
问题是CommonPanel
的构造函数在将其添加到JFrame
之前被调用,因此它实际上没有窗口或根父级。您可以将CommonPanel
更改为:
class CommonPanel extends JPanel {
JButton btn = new JButton();
CommonPanel() {
add(btn);
}
public void init() {
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...
}
}
然后创建一个:
,而不是添加新的commonPanel
JFrame frame = new JFrame();
CommonPanel panel = new CommonPanel();
frame.add(panel);
panel.init();
PS,非常善于使用单元测试,这是一种很好的做法。