Search code examples
javaswinguser-interfacejtablejscrollpane

JTable autoscroll to the bottom in Java


I would like the JTable to autoscroll to the bottom whenever I add a new column and show the last 10 rows. However, I have the option of scrolling to anywhere I want (mouse listener?). Do you know how to do that? Here's the code I have so far. It builds a JTable and adds a new row for every mouse click on the JButton.

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class sampleGUI extends JFrame implements ActionListener {
    private JButton incrementButton;
    private JTable table;
    private DefaultTableModel model;
    private int count;
    private JScrollPane scroll;


    public sampleGUI() {
        JFrame frame = new JFrame("sample frame");
        frame.setLayout(new BorderLayout());

        incrementButton = new JButton("Increase the count!");

        model = new DefaultTableModel();
        model.addColumn("column 1");
        table = new JTable(model);
        frame.add(incrementButton, BorderLayout.NORTH);
        scroll = new JScrollPane(table)
        frame.add(scroll, BorderLayout.CENTER);

        count = 0;

        incrementButton.addActionListener(this);

        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    @Override
    public synchronized void actionPerformed(ActionEvent e) {
        if (e.getSource() == incrementButton) {
            count++;
            model.addRow(new Object[] { count });
        }
    }

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                sampleGUI gui = new sampleGUI();
            }
        });
    }
}

Thanks!


Solution

  • Required to change selection in JTable, add code line

    table.changeSelection(table.getRowCount() - 1, 0, false, false);
    

    to

    public (synchronized) void actionPerformed(ActionEvent e) {