gpt4 book ai didi

java - 无法设置默认按钮 (btn) : no object to call upon

转载 作者:行者123 更新时间:2023-11-29 04:36:21 24 4
gpt4 key购买 nike

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

  • SwingUtilities.windowForComponent(this)
  • SwingUtilities.getWindowAncestor(this)
  • someJPanelObj.getParent()
  • SwingUtilities.getRootPane(someJButtonObj)

但是他们都返回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 之前被调用,因此它实际上没有窗口或根父级。您可以将 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();

附言,你使用单元测试非常好,这是一个很好的实践。

关于java - 无法设置默认按钮 (btn) : no object to call upon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41311789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com