[英]JTable won't scroll in JScrollPane
我在嘗試使表格滾動時遇到了麻煩。 只是不會。 我查看了其他堆棧答案並嘗試了它們,但是它們沒有用; 我不確定是否與這些解決方案有沖突。
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();
}
}
});
}
代替setBounds()
,按照此處的建議重寫getPreferredScrollableViewportSize()
,並pack()
封閉的頂層容器。 此外, API作者“建議你把組件中JPanel
並設置邊框的JPanel
。”
附錄:當JTable
偵聽其TableModel
,請驗證是否從模型中觸發了正確的事件。 如果擴展AbstractTableModel
,則將使用fireTableXxx()
方法之一。
我需要做的就是在添加數據后(我對表模型:P來說是很新的)調用此函數。fireTableStructureChanged();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.