JPanel中使用Miglayout的多个JTable

时间:2013-03-14 14:22:54

标签: java swing jtable miglayout

我是MigLayout的玩家,所以我需要在一个JPanel中添加多个JTable,但是当我尝试添加多个表时,只显示最后一个表,其他表只标记为JScrollPane边框。我的代码在下面。

 Test() {
    //Panels
    JPanel globalPanel = new JPanel(new MigLayout("fillx","[]","[]50[]"));
    JPanel topPanel = new JPanel (new MigLayout("fillx","40px[]15[grow]","40px[]"));
    JPanel tablePanel = new JPanel (new MigLayout("fillx","[center]","[]"));
    //Components
    JComboBox boxProj;
    JTable table;
    JScrollPane scroll;


    //Top Panel        
    topPanel.add(new JLabel("Project Name:"));
    String listString[] = {"test"};
    boxProj= new JComboBox(listString);
    topPanel.add(boxProj);

    //Table Panel
    //Tables
    table = new JTable();
    createTable(table); //my table

    //Adding Multiples Tables
    tablePanel.add( new JScrollPane(table),"growx,wrap,hmax 300");
    tablePanel.add( new JScrollPane(table),"growx,wrap,hmax 300");

    //Scroll to TablePanel
    scroll = new JScrollPane(tablePanel);
    scroll.setBorder(BorderFactory.createTitledBorder(null, "Project", TitledBorder.LEFT, TitledBorder.TOP, new Font("null", Font.BOLD, 12), Color.BLACK));
    scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

    //Global Panel
    globalPanel.add(topPanel, "dock north");
    JSeparator separator = new JSeparator();
    globalPanel.add(separator,"growx");
    globalPanel.add(scroll,"dock south, growx");

    getContentPane().add(globalPanel);
    pack();
    setSize(1024,768);
}

如果我犯了一些错误,请纠正我。

谢谢!

2 个答案:

答案 0 :(得分:2)

任何Swing组件只能有一个父组件。在这里,您将相同的JTable添加到2个不同的JScrollPane容器中。结果是只显示最后一个。要显示2个JTable个组件,您必须创建2个单独的组件。

table2 = new JTable();
...
tablePanel.add(new JScrollPane(table2), "growx,wrap,hmax 300");  

答案 1 :(得分:2)

您似乎尝试两次添加相同的组件。您只能在一个容器中显示一个组件:

table = new JTable();     CREATETABLE(表); //我的桌子

//Adding Multiples Tables
tablePanel.add( new JScrollPane(table),"growx,wrap,hmax 300");
tablePanel.add( new JScrollPane(table),"growx,wrap,hmax 300");

尝试:

JTable table1 = new JTable();
JTable table2 = new JTable();
createTable(table1); //my table
createTable(table2);

//Adding Multiples Tables
tablePanel.add( new JScrollPane(table1),"growx,wrap,hmax 300");
tablePanel.add( new JScrollPane(table2),"growx,wrap,hmax 300");