Search code examples
javaswingjscrollpanelayout-managergridbaglayout

JTable does not fill JScrollPane which is added to JPanel using GridBagLayout


I have a JPanel with GridBagLayout. The panel contains 2 rows, first row has a JLabel and second row has a JScrollPane with JTable inside. The table does not fill 100% of the scrollpane. Even I resize my frame, the scrollpane resizes but the table inside always has fixed width.

JTable table=new JTable(myModel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); 
JScrollPane scroll=new JScrollPane(table);

JPanel panel=new JPanel(new GridBagLayout());
// component add details skipped

And the following are the grid bag constraints applied to scroll pane while adding to panel.

GridBagConstraints gbc=new GridBagConstraints();
gbc.gridx=0; // first column
gbc.gridy=1; // second row
gbc.gridwidth=1;
gbc.gridheight=1;
gbc.fill=GridBagConstraints.BOTH;
gbc.anchor=GridBagConstraints.NORTHEAST;
gbc.weightx=1.0;
gbc.weighty=1.0;

What went wrong? Problem is with scroll pane or table?


Solution

  • Thanks for giving valuable suggestions. I found the exact solution for this problem. Size the table at its preferred size or view port size whichever is greater. Regardless of whatever layout manager you use it is working fine!

    The solution is have table defined with getScrollableTracksViewportWidth() method, as example given below:

    JTable table=new JTable(myModel){
     public boolean getScrollableTracksViewportWidth() {
       return getPreferredSize().width < getParent().getWidth();
     }
    };
    JScrollPane scroll=new JScrollPane(table);