Swing Dynamic JTable创建

时间:2014-03-14 08:40:16

标签: java swing dynamic jtable

我想根据输入动态创建表。如果输入为5,则将有5 JTable s,然后我应该能够唯一地识别这5个表,以便我可以在之后单独处理这5个表。

我在做

table=new Jtable()

,但我想要

table1=new Jtable(),table2=new Jtable(),table3=new Jtable()

等因此自动生成。输入的上限为18。

我该怎么做?

2 个答案:

答案 0 :(得分:0)

尝试这样的事情(未经测试):

ArrayList<JTable> tables = new ArrayList<JTables>();
for(int i=0; i<5; i++) {
  tables.add(new JTabel());
}

答案 1 :(得分:0)

这个怎么样:

ArrayList<JTable> tables = new ArrayList<JTable>();
for (int i = 0; i < 18; i++) {
    tables.add(new JTable());
}

private JComponent createGUI() {
    JPanel pnl = new JPanel();
    for (JTable jTable : tables) {
        pnl.add(jTable);
    }
    return pnl;
}

更新示例:

public class Display extends JFrame {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Display().setVisible(true);
            }
        });
    }

    private ArrayList<JTable> tables = new ArrayList<JTable>(){{
        for (int i = 0; i < 18; i++) {
            add(new JTable(new DefaultTableModel(3,3)));
        }
    }};

    public Display() {
        super("Title");
        this.setSize(832, 594);
        this.setLocationRelativeTo(null); // to center frame on screen
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        JPanel content = new JPanel();
        content.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
        for (JTable table : tables) {
            content.add( createGUI(table) );
        }

        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(content, BorderLayout.CENTER);
    }

    private JPanel createGUI(JTable table) {
        JPanel pnl = new JPanel(new BorderLayout());
        pnl.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
        pnl.add(table.getTableHeader(), BorderLayout.NORTH);
        pnl.add(table, BorderLayout.CENTER);
        return pnl;
    }

}