Search code examples
javaswingjtablejscrollpane

How to add horizontal/vertical scrollbars to JScrollPane


I want to add horizontal scrollbars to my JScrollPane, because my table right now looks like the one below:

enter image description here

Here is my code to create the table:

  this.table = new JTable();
  this.table.setShowGrid(false);
  this.table.getTableHeader().setFont(ReportViewConstants.TABLE_FONT);
  this.table.setFont(ReportViewConstants.TABLE_FONT);

  this.scrollPane = new JScrollPane(this.table);
  Dimension size = new Dimension(300, 400);
  this.scrollPane.setPreferredSize(size);
  this.scrollPane.setMinimumSize(size);
  this.scrollPane.getViewport().setBackground(Color.WHITE);

Can you point out what I'm doing wrong? When I changed the line to create a JScrollPane to:

  this.scrollPane = new JScrollPane(this.table,
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
    JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

The scrollbars are there, but I still cannot scroll horizontally. See the screenshot below.

enter image description here

Thanks!


Solution

  • You have to set for JTable#setAutoResizeMode, more is described in JTable's tutorial Setting and Changing Column Widths