gpt4 book ai didi

java - JTable 中的垂直滚动条

转载 作者:行者123 更新时间:2023-12-01 15:15:21 25 4
gpt4 key购买 nike

我有一个带有垂直滚动条的 JTable,当我添加新行时,滚动条将移动到新行。问题是滚动条在框架中可见,但我无法滚动它。

这是我创建jtable的方式

           table = new javax.swing.JTable(){
public boolean isCellEditable(int rowIndex, int colIndex) {
return false; //Disallow the editing of any cell
}
};

model = (DefaultTableModel) table.getModel();

table.setRowHeight(20);

selectionModel = table.getSelectionModel();
selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

// Create a couple of columns
model.addColumn("ServerIP");
model.addColumn("Port");
model.addColumn("Number of Request");
JTableHeader header = table.getTableHeader();
Color c = new Color(163, 250, 250);
header.setBackground(c);
pane = new JScrollPane(table);
pane.setViewportView(table);
pane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

table.setFocusable(false);


//when added new row here i call scrollbar


scrollToNewRow(table, rowCount, 1);
rowCount++;




private static void scrollToNewRow(JTable table, int row, int col) {
if (!(table.getParent() instanceof JViewport)) {
return;
}
JViewport viewport = (JViewport)table.getParent();

// This rectangle is relative to the table where the
// northwest corner of cell (0,0) is always (0,0).
Rectangle rect = table.getCellRect(0, 0, true);

// The location of the viewport relative to the table
Point pt = viewport.getViewPosition();

// Translate the cell location so that it is relative
// to the view, assuming the northwest corner of the
// view is (0,0)
rect.setLocation(rect.x-pt.x, rect.y-pt.y);

// Scroll the area into view
viewport.scrollRectToVisible(rect);
}

private static JScrollPane getScrollPane(Component c) {
while ((c = c.getParent()) != null)
if (c instanceof JScrollPane)
return (JScrollPane) c;
return null;
}

最佳答案

您总是为 (0, 0) 处的单元格调用 getCellRect。尝试替换:

Rectangle rect = table.getCellRect(0, 0, true);

与:

Rectangle rect = table.getCellRect(row, col, true);

关于java - JTable 中的垂直滚动条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11682260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com