每当我添加一个新列并显示最后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();
}
});
}
}
谢谢!
答案 0 :(得分:4)
要求change selection in JTable添加代码行
table.changeSelection(table.getRowCount() - 1, 0, false, false);
到
public (synchronized) void actionPerformed(ActionEvent e) {
答案 1 :(得分:1)
您忘记在表格中添加JScrollPane
:
//...
frame.add(new JScrollPane(table), BorderLayout.CENTER);
//...
并且不要忘记
导入javax.swing.JScrollPane;
答案 2 :(得分:1)
每当我添加新列
时,我希望JTable自动滚动到底部
我认为你的意思是在添加新行时滚动到底部?
model.addRow(new Object[] { count });
table.scrollRectToVisible(...);