简体   繁体   English

Jtable 不在运行时添加行

[英]Jtable is not adding row in runtime

Im trying to add a row during runtime but it keeps breaking.我试图在运行时添加一行,但它一直在中断。 This is just a simple test to get everything working.这只是一个让一切正常工作的简单测试。 It only will show everything once it has added everything to the table, but sits with a black window until then.它只会在将所有内容添加到表格后才会显示所有内容,但在此之前会显示一个黑色窗口。

public static void main(String[] args) throws IOException, InterruptedException{
    JFrame dashboard = new JFrame("Dashboard");
    dashboard.setVisible(true); 
    dashboard.setTitle("Dashboard Information");
    dashboard.setBounds((960 - 250), (540 - 250), 500, 500);

    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
    dashboard.add(new JScrollPane(table));

    model.addColumn("Col2");
    model.addColumn("Col1");
    model.addColumn("Col3");
    model.addRow(new Object[] {"test", 1, "test"});
    for (int i = 0; i < 10; i++) {
        model.addRow(new Object[] {"test2", 2, "test2"});
        Thread.sleep(100);
    }

    dashboard.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    dashboard.pack();

    }

the Jframe is only packed after we add the rows which means that the table does not appear because we have not made it yet! Jframe仅在我们添加行Jframe被打包,这意味着该表不会出现,因为我们还没有完成它! Moving the dashboard.pack() or the Jframe.pack() to above the loop and below the dashboard.add(new JScrollPane(table));dashboard.pack()Jframe.pack()到循环上方和dashboard.add(new JScrollPane(table));下方dashboard.add(new JScrollPane(table)); first makes the table so it exists, then correctly adds rows during runtime.首先使表存在,然后在运行时正确添加行。

public static void main(String[] args) throws IOException, InterruptedException{
    JFrame dashboard = new JFrame("Dashboard");
    dashboard.setVisible(true); 
    dashboard.setTitle("Dashboard Information");
    dashboard.setBounds((960 - 250), (540 - 250), 500, 500);

    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
    dashboard.add(new JScrollPane(table));
    //move lines to here
    dashboard.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    dashboard.pack();

    model.addColumn("Col2");
    model.addColumn("Col1");
    model.addColumn("Col3");
    model.addRow(new Object[] {"test", 1, "test"});
    for (int i = 0; i < 10; i++) {
        model.addRow(new Object[] {"test2", 2, "test2"});
        Thread.sleep(100);
    }
    //put these lines beofore we add rows to the table
    //dashboard.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //dashboard.pack();

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM