Search code examples
javaswingjtablejpaneljscrollpane

JTable not displaying in the initialization


I'm having a rare problem with this. When I put the code in a button´s event it works and the table is properly displayed, but when I place it below the initComponents() function (inside the constructor) it does not work.

String[] columnNames = {"Nick", "E-Mail"};
Object[][] data = {
{"Kathy", "[email protected]"},
{"John", "Doe"},
{"Sue", "Black"},
{"Jane", "White"},
{"Joe", "Brown"}

};

   jPanel1.setLayout(new BorderLayout()); 
   JTable table = new JTable(data, columnNames);
   Dimension dim = new Dimension(jPanel1.getWidth(),jPanel1.getHeight());
   JScrollPane tableScroll = new JScrollPane(table);
   tableScroll.setPreferredSize(dim);
   jPanel1.add(tableScroll, BorderLayout.CENTER);
   jPanel1.validate();

Any ideas?


Solution

    • replace Dimension dim = new Dimension(jPanel1.getWidth(),jPanel1.getHeight());

    • because before JFrame.pack() or JFrame.setVisible(true) returns zero dimension [0, 0]


    • with table.setPreferredScrollableViewportSize(table.getPreferredSize());