简体   繁体   English

JTable自动滚动到Java底部

[英]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. 每当我添加新列并显示最后10行时,我都希望JTable自动滚动到底部。 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. 它会建立一个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();
            }
        });
    }
}

Thanks! 谢谢!

Required to change selection in JTable , add code line 更改JTable中的选择所需,添加代码行

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

to

public (synchronized) void actionPerformed(ActionEvent e) {

You forget add JScrollPane to the table : 您忘记将JScrollPane添加到表中:

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

and don't forget 别忘了

import javax.swing.JScrollPane; 导入javax.swing.JScrollPane;

I would like the JTable to autoscroll to the bottom whenever I add a new column 每当我添加新列时,我都希望JTable自动滚动到底部

I assume you mean scroll to the bottom when you add a new row? 我假设您的意思是添加新行时滚动到底部?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM