2012-07-27 251 views
0

我有一个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; 
} 
+1

您是否尝试过'JComponent.scrollRectToVisible'不是/以及?可能做了很多你已经在做的事情,但干草 – MadProgrammer 2012-07-27 06:25:33

+2

请不要在代码中混合使用空格和制表符,SO格式化程序无法处理它并产生我们都难以忍受的混乱;-) – kleopatra 2012-07-27 08:48:55

回答

1

你一直在呼吁getCellRect的细胞(0,0)。尝试更换:

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

有:

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

问题是因为我的维度现在我改变了pane.setPreferredSize(new Dimension(450,200));现在它的工作 – 2012-07-27 07:22:39

+4

@ Mr.Cool严重怀疑这是一个“解决方案”:如果setXXSize似乎可以解决问题,那么在你的代码中出现了一些问题:-)顺便说一句,你所有的计算都不需要 - 只需要抓住cellRect并调用** table * * .scrollRectToVisible(cellRect) – kleopatra 2012-07-27 08:46:24

+0

@ kleopatra -i dnt与scrollToNewRow函数有任何问题,我错误地设置了滚动条属性,所以这个原因我不能看到滚动条,现在我改变了我先前说的。现在它的工作。 – 2012-07-27 10:50:09