2

我一直无法让表格滚动;它只是不会。我查看了其他堆栈答案并尝试了它们,但它们不起作用;而且我不确定我是否与这些解决方案有冲突。

tableModel = new TableModel(); //Custom Table Model
table = new JTable();
table.setBorder(null);
table.setFillsViewportHeight(true);
table.setModel(tableModel);

JScrollPane tblScrollPane = new JScrollPane(table);
tblScrollPane.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
tblScrollPane.setBounds(245, 17, 560, 425);
frmServerAdministration.getContentPane().add(tblScrollPane);

编辑:更多信息

因此会打开一个窗口,它是服务器程序。客户端程序连接到服务器,当它们连接到服务器时,会在我的表模型类中触发一个方法,该方法会在表中添加一个新行。(我可以看到该行)然后在该方法结束时它调用另一个但 ScrollPane 中没有任何变化。我需要重新粉刷吗?-

Server.updateTableScroll();

public static void updateTableScroll() {
    System.out.println("Here"); //NOTE: I do see this printed out
    int last = table.getModel().getRowCount() - 1;
    Rectangle r = table.getCellRect(last, 0, true);
    table.scrollRectToVisible(r);        
}

编辑2:想法

所以在 Eclipse 中我使用 Window Builder 来制作 GUI,下面的 for 循环将显示带有滚动条的表格!但是当我在另一点运行相同的 addClient() 方法时,滚动条将不会出现。

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Server window = new Server();
                window.frmServerAdministration.setVisible(true);
                for(int i = 0; i < 20; i++){
                    tableModel.addClient(i, String.valueOf(i));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
4

2 回答 2

4

而不是setBounds(), override getPreferredScrollableViewportSize(),如建议的here,以及pack()封闭的顶级容器。此外,API作者“建议您将组件放在 a 中JPanel并在 . 上设置边框” JPanel

附录:当 aJTable监听它的TableModel时,验证模型是否触发了正确的事件。如果您扩展AbstractTableModel,其中一种fireTableXxx()方法将是合适的。

于 2013-08-06T00:01:30.323 回答
1

我需要做的就是在添加数据后调用它(我对表模型很陌生:P) this.fireTableStructureChanged();

于 2013-08-06T02:17:18.613 回答