1

每当我添加新列并显示最后 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();
            }
        });
    }
}

谢谢!

4

3 回答 3

5

需要更改 JTable 中的选择,添加代码行

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

public (synchronized) void actionPerformed(ActionEvent e) {
于 2013-05-03T16:54:06.107 回答
1

每当我添加新列时,我希望 JTable 自动滚动到底部

我假设您的意思是在添加新行时滚动到底部?

model.addRow(new Object[] { count });
table.scrollRectToVisible(...);
于 2013-05-03T19:57:07.170 回答
0

You forget add JScrollPane to the table :

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

and don't forget

import javax.swing.JScrollPane;

于 2013-05-03T16:01:33.457 回答