2012-01-19 74 views
0

可能這是一個簡單的錯誤,但我不明白什麼是錯的。我有一個類創建一個框架(MainFrame)並使用方法來更改面板。我還有另外一門課,其中有小組描述。但是,由於某種原因,我只能看到沒有面板的框架。有人能幫我在這裏嗎?我在MigLayout新,和將是真正偉大的,如果你能解釋我的錯誤..框架不顯示面板使用MigLayout

public class MainFrame extends JFrame 
{ 
private JPanel panel; 

//getting dimensions 
public static Dimension dim = Toolkit.getDefaultToolkit().getScreenSize() ; 

public MainFrame() 
{ 
    getContentPane().setLayout(new MigLayout()); 
    setDefaultCloseOperation(DISPOSE_ON_CLOSE); 

    this.setTitle("Title"); 
    this.setLocation((int)dim.getWidth()/3,(int)dim.getHeight()/4); 
    this.setSize(500, 500);  

    setNewPanel(new MainWindowPanel()); 
    this.validate(); 
} 

public final void setNewPanel(JPanel newPanel) 
{ 
    //to change the panel, old one has to be deleted 
    if (panel != null) remove(panel); 

    getContentPane().setLayout(new MigLayout()); 
    add(newPanel); 

    //pack(); 
    panel = newPanel; 
    this.setVisible(true); 
} 
} 

我的面板類

public class MainWindowPanel extends JPanel 
    { 
//Label 
JLabel greeting = new JLabel("Welcome:"); 

//Buttons 
JButton helpButton = new JButton("Help?"); 

public MainWindowPanel() 
{ 

    // the layout of the main screen 
    JPanel p = new JPanel(new MigLayout("fill", "[center]")); 

    p.setBackground(Color.lightGray); 
    p.add(greeting, "skip 1, gaptop 40, wrap"); 
    greeting.setFont(times20); 

    p.add(helpButton, "bottom, span, tag help"); 

    } 
} 

謝謝!!

在MainWindowPanel的構造

回答

2

您創建一個新的面板和按鈕/標籤添加到 - 而無需添加新創建的面板。添加以下行:

add(p); 

其實,我不太明白你想要的那些深層嵌套面板,達到何不

public MainWindowPanel() { 
     setLayout(new MigLayout(... contraints); 
     add(greetings); 
     add(button); 
} 

而當你在它:考慮擴展JPanel但使用它:

JComponent mainWindowPanel = new JPanel(new MigLayout(...)); 
JLabel greetings = ... // create and configure 
mainWindowPanel.add(greetings); 
JButton button = ... // create and configure 
mainWindowPanel.add(button); 
+0

非常感謝!工作:) – cranberry

+0

老實說,你的建議剛剛救了我的一天! :)我無法弄清楚如何將面板拉伸到框架,但是一旦我用你的建議來省略這些嵌套面板,一切都變得很好,清晰:)。萬分感謝! – cranberry