2013-03-04 76 views
0

我瞭解JTabbedPane和GridBagLayout背後的概念。但是,當我嘗試將兩者一起使用時,我就失敗了。也就是說,當我使用GBLayout時,我的其他選項卡(每個選項卡具有不同的功能)都沒有顯示出來。請幫忙。謝謝。JTabbedPane與GridBagLayout

這裏是我的代碼:

import java.awt.*; 
    import javax.swing.*; 

    public class Tryout extends JFrame { 

    private static final long serialVersionUID = 1L; 
    private  JTabbedPane tabbedPane; 
    private  JPanel  panel1; 
    private  JPanel  breakfast; 

    public Tryout() 
    { 
     JPanel topPanel = new JPanel(); 
     topPanel.setLayout(new BorderLayout()); 
     getContentPane().add(topPanel); 

     createPage1(); //Tab1 
     createPage2(); //Tab2 

     tabbedPane = new JTabbedPane(); 
     tabbedPane.addTab("Input Form", panel1); 
     tabbedPane.addTab("Breakfast", breakfast); 
     topPanel.add(tabbedPane, BorderLayout.CENTER); 
    } 

    public void createPage1() 
    { 
     /* Works fine when I un-comment this 
     panel1 = new JPanel(); 
     panel1.setLayout(new BorderLayout()); 
     panel1.add(new JLabel("Hi"), BorderLayout.NORTH); 
     */ 
     //Tabs not getting displayed if I add the code below with GBLayout 
     JPanel panel = new JPanel(new GridBagLayout()); 
     this.getContentPane().add(panel); 

     JLabel label = new JLabel("Form"); 

     JPanel tableButtonPanel = new JPanel(); 
     tableButtonPanel.add(new JButton("Add Thing")); 
     tableButtonPanel.add(new JRadioButton("Delete Thing")); 
     tableButtonPanel.add(new JButton("Modify Thing")); 

     GridBagConstraints gbc = new GridBagConstraints(); 

     gbc.gridx = 0; 
     gbc.gridy = 0; 
     panel.add(label, gbc); 

     gbc.gridx = 0; 
     gbc.gridy = 2; 
     panel.add(tableButtonPanel, gbc); 

    } 

    public void createPage2() 
    { 
     breakfast = new JPanel(); 
     breakfast.setLayout(new BorderLayout()); 
     breakfast.add(new JButton("North"), BorderLayout.NORTH); 
     breakfast.add(new JButton("South"), BorderLayout.SOUTH); 
     breakfast.add(new JButton("East"), BorderLayout.EAST); 
     breakfast.add(new JButton("West"), BorderLayout.WEST); 
     breakfast.add(new JButton("Center"), BorderLayout.CENTER); 
    } 

public static void main(String args[]) { 

     Tryout ex = new Tryout(); 
     ex.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     ex.setSize(750,750); 
     ex.setVisible(true); 
     ex.setTitle("Recipe Tracker"); 
     ex.setBackground(Color.gray); 

    } 
} 

回答

3

的問題是,在createPage1,要添加一個新的JPanelJFrame

this.getContentPane().add(panel); 

它替代topPanel(其中包含JTabbedPane)這是在JFrameBorderLayout.CENTER的位置。因此沒有出現JTabbedPane

你可以簡單地回報已創建並把它添加到您的JTabbedPaneJPanel

public JPanel createPage1() { 

    JPanel panel = new JPanel(new GridBagLayout()); 
    // this.getContentPane().add(panel); don't do this... 
    ... 

    return panel; 
} 

,並添加:

tabbedPane.addTab("Input Form", createPage1()); 
+0

保釋我出去。非常感謝。但是,我現在還沒有其他問題。 – trollster 2013-03-19 10:10:33