0

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();

    }
  • Well, you're violating the single threaded nature of the API to begin with – MadProgrammer Jan 03 '19 at 04:11
  • 1
    works fine for me.. may be your system is taking too long to render it.. try changing to `Thread.sleep(2000);` to give it time to render.. also move the last 2 statements before the for-loop because you're blocking the main thread – Kartik Jan 03 '19 at 04:12
  • [As a more accurate example](https://stackoverflow.com/questions/17414109/populate-jtable-with-large-number-of-rows/17415635#17415635) this will allow add rows to the table from a background thread, in away that does not violate the single threaded nature of the API – MadProgrammer Jan 03 '19 at 04:13

1 Answers1

0

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();

    }