0
votes

Trying to have a JTable inside a JScrollPane. But the problem is, every time I add another row to the table, the JFrame increases in size, height-wise (screenshot below for reference). I don't want it to do this. Obviously, since it's in a scroll pane, if I keep adding rows to the table, I want a scrollbar to actually be shown and used to scroll down to see the lower values in the table.

Screenshot: http://i.imgur.com/dUqQW7N.jpg

Code:

String[] columns = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};

Object[][] data = {
        {"Kathy", "Smith", "Snowboarding", 5, false},
        {"John", "Doe", "Rowing", 3, true},
        {"Sue", "Black", "Knitting", 2, false},
        {"Jane", "White", "Speed reading", 20, true},
        {"Joe", "Brown", "Pool", 10, false}
};

searchBox = new JTextField();
searchButton = new JButton();
rentCarButton = new JButton();
rentedCarsButton = new JButton();
table = new JTable(data, columns);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
scrollPane = new JScrollPane(table);

Any help would be greatly appreciated.

1
You never add anything to the table after it's been created in the code you posted. Post a complete, minimal example that reproduces the problem.JB Nizet
That's not the point. The point isn't that I am going to be using dynamic methods to add rows to the table, it's that scroll pane and table aren't performing the way I want them. I have tested this same solution, but added more rows to the "data" object multidimensional array and I saw that the JFrame was being stretched out. I want a solution that actually uses the scrollbar from the scroll pane.Jacob
Then don't use table.getPreferredSize() as the preferred scrollable viewport size. The preferred size of the table is the size that allows it to display all its rows. Use the fixed dimension you want.JB Nizet
More here.trashgod

1 Answers

0
votes

Welp the answer was right in front of me, I just changed the line of code

table.setPreferredScrollableViewportSize(table.getPreferredSize());

to

table.setPreferredScrollableViewportSize(new Dimension(400, 100));

I feel dumb.