【问题标题】:vertical scroll bar in JTableJTable中的垂直滚动条
【发布时间】:2012-07-27 06:00:19
【问题描述】:

我有一个带有垂直滚动条的 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?可能做了很多你已经在做的事情,但是干草
  • 请不要在代码中混用空格和制表符,SO 格式化程序无法处理它并产生我们都痛苦看到的混乱 ;-)

标签: java swing jtable awt jscrollpane


【解决方案1】:

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

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

与:

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

【讨论】:

  • 问题是因为我的尺寸现在我改变了 pane.setPreferredSize(new Dimension(450, 200));现在它正在工作
  • @Mr.Cool 严重怀疑这是一个“解决方案”:如果 setXXSize 似乎可以解决问题,那么您的代码中有问题:-) 顺便说一句,您不需要所有计算 - 只需抓住 cellRect 并调用表格.scrollRectToVisible(cellRect)
  • @kleopatra-i dnt 对 scrollToNewRow 函数有任何问题,我错误地设置了滚动条属性,所以我现在看不到滚动条,我改变了我之前所说的内容。现在它正在工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多