我有一個JTable與垂直滾動條上,當我添加新行滾動條將移動到新行。問題是滾動條在框架中可見,但我無法滾動它。垂直滾動條在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;
}
您是否嘗試過'JComponent.scrollRectToVisible'不是/以及?可能做了很多你已經在做的事情,但乾草 – MadProgrammer 2012-07-27 06:25:33
請不要在代碼中混合使用空格和製表符,SO格式化程序無法處理它併產生我們都難以忍受的混亂;-) – kleopatra 2012-07-27 08:48:55