2014-03-03 59 views
-1

我似乎無法將JButton添加到JPanel。 我有一個PropWindow(JFrame),它有一個PropView(JPanel)。 PropView-JPanel似乎被正確添加,因爲我可以使用paint()在其上繪製形狀。 但是,當我使用它來嘗試添加一個按鈕,它只是不會出現ATT所有:/JButton添加到JPanel不顯示

JButton testButton; 

public PropView(int width, int height) { 
    super(true); 

    setLayout(null); 
    setSize(width, height); 

    //TestButton 
    testButton = new JButton("Test"); 
    testButton.setLocation(10,10); 
    testButton.setSize(100, 50); 
    testButton.setVisible(true); 

    add(testButton); 

    setFocusable(true); 
    setVisible(true); 
} 

JFrame中和的JPanel均爲250x600像素。

+1

在您的文章沒有顯示的理由爲自己的錯誤。我建議1)您考慮創建併發布[最小示例程序](http://stackoverflow.com/help/mcve)。 2)避免使用空白布局和像瘟疫一樣的絕對定位,因爲這會讓你陷入困境。 –

+0

你試過把按鈕添加到'JFrame'嗎? – BitNinja

+1

顯示你的油漆代碼,這可能會搞砸了,特別是如果你使用錯誤的油漆方法。 – NESPowerGlove

回答

-1

確保您使用myPropWindow.getContentPane().add(myPropPanel)將PropPanel添加到PropWindow,而不僅僅是myPropWindow.add(myPropPanel)

+1

這個建議是保證不會有幫助,因爲這兩個調用完全相同的事情。請刪除或改進此答案。 –

+0

真的嗎?呵呵。直到我切換到內容窗格而不是窗口根目錄時,我總是遇到麻煩,但也許我做了其他錯誤。 –

+1

不要拿我的話 - 看看'add(...)'方法的JFrame API部分。我引用''作爲一種方便添加及其變體,必要時remove和setLayout已被覆蓋以轉發到contentPane。「' –

0

我不能從你發佈的代碼片段中知道,但以防萬一:確保你在框架上調用pack()你已添加面板或任何其他組件。

此外,通常不鼓勵擴展JPanel或JFrame,除非您有充足的理由這樣做,只是一個頭。

Here您對顯示幀一個簡短的教程:

,並在其中一些示例代碼,這可能有助於:

//1. Create the frame. 
JFrame frame = new JFrame("FrameDemo"); 

//2. Optional: What happens when the frame closes? 
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

//3. Create components and put them in the frame. 
//...create emptyLabel... 
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER); 

//4. Size the frame. 
frame.pack(); 

//5. Show it. 
frame.setVisible(true);