2014-07-22 105 views
1

我想將幾個組件添加到JPanel中,然後將面板添加到JFrame中。將幾個組件添加到Jpanel中

這裏是一個簡短的示例程序:

public class Test extends JPanel { 

    private static final long serialVersionUID = -5616883761578620198L; 

    static JPanel jpanel; 
    private static JLabel jLabel; 

    private static void createAndShowGUI() { 
     JFrame frame = new JFrame("Test"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     //adding everything to the jpanel 
     jpanel = new JPanel(); 
     jpanel.add(addLabel()); 
     jpanel.add(addTable()); 

     //adding the jpanel to the frame 
     frame.add(jpanel); 

     frame.pack(); 
     frame.setVisible(true); 
    } 

    public static Component addTable() { 

     jLabel = new JLabel("Test"); 

     String[] columnNames = {"First Name", 
       "Last Name", 
       "Sport", 
       "# of Years", 
     "Vegetarian"}; 

     Object[][] data = { 
       {"Kathy", "Smith", 
        "Snowboarding", new Integer(5), new Boolean(false)}, 
        {"John", "Doe", 
         "Rowing", new Integer(3), new Boolean(true)}, 
         {"Sue", "Black", 
          "Knitting", new Integer(2), new Boolean(false)}, 
          {"Jane", "White", 
           "Speed reading", new Integer(20), new Boolean(true)}, 
           {"Joe", "Brown", 
            "Pool", new Integer(10), new Boolean(false)} 
     }; 

     final JTable table = new JTable(data, columnNames); 
     table.setPreferredScrollableViewportSize(new Dimension(500, 70)); 
     table.setFillsViewportHeight(true); 

     JScrollPane scrollPane = new JScrollPane(table); 

     table.add(scrollPane); 

     return this; //do not know how to return the whole component? 
    } 

    public static Component addLabel() { 

     jLabel = new JLabel("Test1"); 

     return jLabel; 
    } 


    public static void main(String[] args) { 
     javax.swing.SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       createAndShowGUI(); 
      } 
     }); 
    } 
} 

但是,我得到異常:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: adding container's parent to itself 

任何建議如何解決呢?

+0

您要添加表到滾動窗格,然後加入滾動窗格到桌上?那是你的意思嗎? –

+0

只要擺脫'table.add(scrollpane)'並返回滾動窗格 –

回答

1

事業這條線的return this; //do not know how to return the whole component?

您返回本 - >這是一個JPanel,因爲你從JPanel的繼承類

+0

Thx爲您的答案!任何修復建議? – mrquad

+1

當然,我會提前寫一個新的答案 – romaneso

+0

Thx爲您提供幫助! – mrquad