javaswingjtablejscrollpane

Swing - remove extra space from JScrollPane so that it only fits the table rows


I am a newbie to swing. I have created a table from an array list of objects. I want to know how I can remove the access white space from bellow the table- that is adjust the size of the JScrollPane so that it fits the table without leaving any extra space.

https://i.sstatic.net/YQoxg.png

Here's my code

import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
public class PersonTableModel extends AbstractTableModel{


    private String[] columnNames = {"Name","Date of Birth","Type"};
    private ArrayList<Person> list;

    public PersonTableModel(ArrayList<Person> personList){
        this.list = personList;
    }

    @Override
    public int getRowCount() {
        return list.size();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Object temp = null;
        if (columnIndex == 0) {
            temp = list.get(rowIndex).getName();
        }
        else if (columnIndex == 1) {
            temp = list.get(rowIndex).getDOB().getDate();
        }
        else if (columnIndex == 2) {
            if(list.get(rowIndex) instanceof Teacher)
                temp = "Teacher";
            else
                temp = "Student";
        }
        return temp;
    }

    public String getColumnName(int col) {
        return columnNames[col];
    }
}

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.util.ArrayList;
public class PersonTable extends JFrame{

    JTable myTable;
    PersonTableModel tableModel;
    ArrayList<Person> list;

    // contructor
    public PersonTable(ArrayList<Person> list){
        this.list = list;
        tableModel = new PersonTableModel(list);
        myTable =  new JTable(tableModel);

        setBounds(10,10,600,600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JScrollPane scrollPane = new JScrollPane(myTable);

        JPanel panel = new JPanel();
        panel.add(scrollPane);
        add(panel,BorderLayout.CENTER);

    }
}

Thanks in advance.


Solution

  • After setting the model of the table you can use:

    myTable.setPreferredScrollableViewportSize(myTable.getPreferredSize());
    

    Also, instead of using setBounds(...) you would need to add:

    pack() 
    

    at the bottom of the constructor, so the frame can be sized properly.

    Note, this works for tables with limited rows. For a large table you may want to limit the number of rows displayed before scrolling is required. In this case you can override the getPreferredScrollableViewportSize() method as demonstrated in:

    JTable inside JScrollPane inside JPanel with GridBagLayout, doesn't look as it should