Java Swing How to - Make JTable both AutoResize and horizontal scrollable








Question

We would like to know how to make JTable both AutoResize and horizontal scrollable.

Answer

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
/*  w w  w. j  a  v a 2 s . c  o m*/
public class Main extends JFrame {
  public Main() {
    final JTable table = new JTable(10, 5) {
      public boolean getScrollableTracksViewportWidth() {
        return getPreferredSize().width < getParent().getWidth();
      }
    };
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    final JScrollPane scrollPane = new JScrollPane(table);
    getContentPane().add(scrollPane);
  }

  public static void main(String[] args) {
    Main frame = new Main();
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.pack();
    frame.setSize(400, 300);
    frame.setVisible(true);
  }
}