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

Can't setDefaultButton(btn): no object to call upon

我只想将某些 JButton 设置为默认按钮(即当按下 ENTER 时,它会执行其操作)。跟随 this answer 和其他几个人,我都试过了:

但他们都return null...

代码如下:

public class HierarchyTest {
    @Test
    public void test(){
        JFrame frame = new JFrame();
        frame.add(new 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...
    }
}

问题是 CommonPanel 的构造函数在您将其添加到 JFrame 之前被调用,因此它实际上没有 window 或根父级。您可以将 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,你使用单元测试非常好,这是一个很好的实践。