Search code examples
javaswingjtablejscrollpane

JTable is not showing result after update?


I am creating a table at run time after fetching the result from the database. The flow of my application is like this.

  1. Initializing a empty JScrollPane(); JScrollPane tableScroll = new JScrollPane();
  2. Fetching result from the database;
  3. Updating result to JTable and adding JTable to JScrollPane using following method:

Code:

private void setResultTable(Vector documents, Vector header) {
   TableModel model = new DefaultTableModel(documents, header);
   documentTable.setModel(model);
   tableScroll.add(documentTable);
   tableScroll.repaint();
}

my problem is that after calling setResultTable the result are not appearing in the table. Please help me with that. Thanks in advance !!!


Solution

  • You appear to be adding the JTable directly to the JScrollPane. If so this isn't correct and you'll want to change this so that you're actually adding the table to the scroll pane's viewport:

    tableScroll.getViewport().add(documentTable);
    

    There is no need to repaint the JScrollPane after doing this.

    For example:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    
    public class AddTableToScroll {
       public static void main(String[] args) {
          final JScrollPane sPane = new JScrollPane();
    
          // Sorry Jeanette!!
          sPane.setPreferredSize(new Dimension(200, 150));
    
          JButton button = new JButton(new AbstractAction("Press Me!") {
    
             public void actionPerformed(ActionEvent arg0) {
                DefaultTableModel model = new DefaultTableModel(new Integer[][] {
                      { 1, 2 }, { 3, 4 } }, new String[] { "A", "B" });
                JTable table = new JTable(model);
    
                sPane.getViewport().add(table);
    
             }
          });
    
          JPanel panel = new JPanel();
          panel.add(sPane);
          panel.add(button);
    
          JOptionPane.showMessageDialog(null, panel);
    
       }
    }
    

    If this doesn't help, you'll want to also tell us exactly what happens, what you see, and if possible supply us with a small compilable runnable program that demonstrates your problem, an SSCCE