我只想設置某個JButton
作爲默認按鈕(即當按下ENTER
時,它執行其操作)。繼this answer和其他幾個人,我想他們都:Can not setDefaultButton(btn):no object to call upon
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());
}
}
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 – Tar