paul62285
paul62285

Reputation: 21

Java JTable data loading

so i have a large cardlayout with one panel as a JTable:

tbm = new DefaultTableModel();  
tbm.addColumn("Account Number"); 
tbm.addColumn("PIN"); 
tbm.addColumn("Access Level"); 
tbm.addColumn("Balance");
table = new JTable(tbm);
JScrollPane scrollPane = new JScrollPane(table);

under actionPerformed, I am trying to load some data into the table as follows:

else if(event.getSource() == listallButton) {
      String query = "SELECT * FROM ATM";
      String delimiter = ",";
      String input = "go";
      int count=0;
      al = new ArrayList<String>();

          try {
              communicationObject = new DataObject();
              communicationObject.setMessage(query);
              Socket socketToServer = new Socket("sunlab32.njit.edu",31414);
              ObjectOutputStream myOutputStream = new ObjectOutputStream(socketToServer.getOutputStream());
              ObjectInputStream myInputStream = new ObjectInputStream(socketToServer.getInputStream());
              myOutputStream.writeObject(communicationObject);
              communicationObject = (DataObject)myInputStream.readObject();
              input = communicationObject.getMessage();
              if (input != "stop") {
                  al.add(input);
                  data[count] = input;
                  count++; }

              for (int i=0;i<data.length;i++) {
                  row = data[i];
                  temp = row.split(delimiter);
                  tbm.addRow(new String[] {temp[0],temp[1],temp[2],temp[3]}); } 
              tbm.fireTableDataChanged();
              table.repaint();

now my problem is that the table does not get repainted after all the rows are loaded...any suggestions?

Upvotes: 1

Views: 2086

Answers (2)

tenorsax
tenorsax

Reputation: 21223

There is no need to call tbm.fireTableDataChanged();. The model itself will notify the table in response to addRow(). And if the table and model are connected correctly the table will refresh itself.

You may find this example helpful, it demos use of DefaultTableModel.

As this code is not visible, make sure the table and scroll pane are setup correctly. Also, make sure your query actually returns data.

Upvotes: 1

mprabhat
mprabhat

Reputation: 20323

tbm.addModel should be firing table changed event, so tbm.fireTableDataChanged is not necessary.

You can try doing this though to force it to paint itself after you have added all the rows.

table.setModel(tbm);

Off topic:

Swing is a single threaded event model, which means the task that you are carrying out will block UI update.

I would suggest you move your data loading to SwingWorker and once you are done with your changes push the data on the UI. Take a look at this tutorial

Upvotes: 4

Related Questions