简体   繁体   中英

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! Moving the dashboard.pack() or the Jframe.pack() to above the loop and below the 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();

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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