【发布时间】:2016-12-24 08:54:12
【问题描述】:
我只想将某些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...
}
}
【问题讨论】:
-
@ItamarGreen,我一回到我心爱的笔记本电脑就试试看:-D