succulentBroccoli
succulentBroccoli

Reputation: 3

Resize JScrollPane (containing a JTable) upon running

I have a basic JFrame - it contains a JTable (enclosed by a JScrollPane automatically added by the NetBeans swing GUI builder, I'd like to keep the scroll pane).

When the frame is instantiated from a button click, the number of rows in the JTable may change depending on which button it was opened from. I want to resize the JTable so it doesn't look silly with extra space if there's only 2 rows. The JScrollPane containing the JTable seems to be what's giving me issues. Here is my code:

public dynamicScrollPaneResize() {
    initComponents();

    exampleTable.setShowGrid(true);

    DefaultTableModel exampleTableModel = (DefaultTableModel)exampleTable.getModel();
    exampleTableModel.setRowCount(0);
    Object[] firstRow = {"Sweater 1","Blue"};
    Object[] secondRow = {"Sweater 2","Purple"};
    exampleTableModel.addRow(firstRow);
    exampleTableModel.addRow(secondRow);

    exampleScrollPane.setPreferredSize(new Dimension(exampleTable.getWidth(),10));
    exampleScrollPane.setMaximumSize(new Dimension(exampleTable.getWidth(),10));
    exampleTable.setFillsViewportHeight(true);

    this.revalidate();
    this.repaint();
}

I try to clear the rows, then add the 2 I want, then resize accordingly. I just threw in 10 as the height because I knew I'd see a difference, which I'm not. If I try to resize the table it works just fine, but resizing the scroll pane has no effect so far.

Upvotes: 0

Views: 428

Answers (1)

WillShackleford
WillShackleford

Reputation: 7018

  1. Go to the Design View
  2. Select the scroll pane in the Navigator window in the lower left.
  3. Right-click for popup menu.
  4. Make sure Auto Resizing -> Horizontal and Auto Resizing -> Vertical are checked.
  5. Add a class variable named paneSize (for example) of type Dimension.
  6. Select Properties for the scroll pane from the pop-up menu.
  7. Click the button with ... next to preferredSize.
  8. Change property using to Custom Code.
  9. In the text field for the custom code put the name of the variable you added. (eg paneSize).
  10. Set paneSize to whatever you want in the constructor before initComponents is called.

Upvotes: 1

Related Questions