无法设置默认按钮(btn):没有要调用的对象

时间:2016-12-24 08:54:13

标签: java swing awt

我只想将某个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...
    }
}

1 个答案:

答案 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,非常善于使用单元测试,这是一种很好的做法。