有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中将JTable autoscroll摆动到底部

每当我添加新列并显示最后10行时,我希望JTable能够自动滚动到底部。但是,我可以选择滚动到任何我想要的地方(鼠标侦听器?)。你知道怎么做吗?这是我到目前为止的代码。它构建一个JTable,并为每次单击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();
            }
        });
    }
}

谢谢


共 (3) 个答案

  1. # 1 楼答案

    您忘记了将JScrollPane添加到表中:

    //...
    frame.add(new JScrollPane(table), BorderLayout.CENTER);
    //...
    

    别忘了

    import javax.swing.JScrollPane;

  2. # 2 楼答案

    需要change selection in JTable,添加代码行

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

    public (synchronized) void actionPerformed(ActionEvent e) {
    
  3. # 3 楼答案

    I would like the JTable to autoscroll to the bottom whenever I add a new column

    我想你的意思是添加新行时滚动到底

    model.addRow(new Object[] { count });
    table.scrollRectToVisible(...);