2016-12-24 93 views
1

我只想設置某個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... 
    } 
} 
+1

@ItamarGreen,一旦我回到我心愛的筆記本電腦,我會嘗試它:-D – Tar

回答

3

的問題是,你把它添加到JFrame之前,所以它真的沒有窗戶,或根父CommonPanel調用構造函數。你可以改變你的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,很不錯的,你要使用單元測試,這是一個很好的做法。

+0

它的工作,但有點尷尬。我必須明確地調用'init()'。是不是有一些我可以重寫的方法,比如'OnLoaded()','OnInitialized()'或類似的東西,這會在JPanel被添加到它的容器後自動調用? – Tar

+0

@Tar我不認爲有 – ItamarG3

+0

@Tar'是不是有一些我可以重寫的方法,比如OnLoaded(),OnInitialized()或類似的東西,它會在JPanel被添加到其容器後自動調用?' - 您可以在面板中添加一個'AncestorListener'並處理'ancestorAdded'事件。 – camickr

相關問題