How to Adjust a JScrollPane based on the JTable's size?

393 Views Asked by At

I have a table right now that's displaying a list of classes and everything works fine except the formatting of it inside of the scroll pane. Here's what I have right now for it.

    String[] columns = {"Class","Period","Size", "Honors/AP"};
    JTable classTable = new JTable(new DefaultTableModel(new Object[][] {}, columns));
    DefaultTableModel model = (DefaultTableModel)classTable.getModel();

    //populating the table based on the number of classes that the teacher has
    for (Class c: t.getClasses()) {
        model.addRow(new Object[]{c.getClassName(),c.getPeriod(),c.getSize(),c.isHonorsAP()});
    }
    if (classTable.getRowCount()==0)
        model.addRow(new Object[]{});

    JScrollPane scrollPane = new JScrollPane(classTable);
    classTable.setPreferredSize(new  Dimension(700,100));
    classTable.setPreferredScrollableViewportSize(classTable.getPreferredSize());
    classTable.setFillsViewportHeight(true);
    if (classTable.getPreferredSize().getHeight() < scrollPane.getPreferredSize().getHeight())
        scrollPane.setPreferredSize(classTable.getPreferredSize());

So the problem on one end is that when there aren't enough rows to fill the preferred size of the table, it leaves extra space at the bottom and I'm trying to get that removed.

And then on the other end, when there are more rows that can fit, I need the size to stay but add in the scroll bar. I'm really confused right now. Any help would be greatly appreciated

0

There are 0 best solutions below