我在JScrollPane中有一个JTable,我想以编程方式滚动到表格的底部。我试过的代码是:
int bottomRow = table.getRowCount()-1;
Rectangle rect = table.getCellRect(bottomRow,0,true);
table.scrollRectToVisible(rect);
我也尝试了代码:
int bottomRow = table.getRowCount()-1;
Rectangle rect = table.getCellRect(bottomRow,0,true);
jscrollPane1.getViewPort().setViewPosition(rect.getLocation());
两个代码片段的行为都相同,两个都是滚动表格而不是底行,而是根据矩形的高度在底行上方几行。
我需要帮助才能在可见矩形中查看表格的最后一行。
答案 0 :(得分:2)
疯狂猜测(因为没有提供足够的上下文),当您收到有关tableModel中的更改的通知时,您希望更新滚动值。
在这种情况下,问题是表本身正在监听模型以更新其内部。由于您希望根据表本身的状态更改某些内容,因此必须确保您的操作仅在内部完全更新后发生,例如:
public void tableChanged(TableModelEvent e) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// scroll to last row
}
});
}
答案 1 :(得分:0)
我写了这个简单的例子来演示一个可行的解决方案,看到这个问题没有进一步的发展,我会把它作为一个工作的例子发布,希望它可以从OP中提示更多的信息
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class ToLastRow {
public static void main(String[] args) {
new ToLastRow();
}
public ToLastRow() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
DefaultTableModel model = new DefaultTableModel(new Object[]{"Look no hands..."}, 0);
for (int index = 0; index < 1000; index++) {
model.addRow(new Object[]{index});
}
final JTable table = new JTable(model);
JButton last = new JButton("Last");
JButton first = new JButton("First");
last.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int row = table.getRowCount() - 1;
scrollTo(table, row);
}
});
first.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
scrollTo(table, 0);
}
});
JPanel buttons = new JPanel();
buttons.add(last);
buttons.add(first);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(table));
frame.add(buttons, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public void scrollTo(JTable table, int row) {
Rectangle bounds = table.getCellRect(row, 0, true);
table.scrollRectToVisible(bounds);
table.addRowSelectionInterval(row, row);
}
}