2012-12-13 16 views
2

我有一個JPanel組件,其內部爲JTable。當我按照下面的代碼運行代碼時,表格會正確呈現和更新。只要我嘗試使用scrollPane方法,表格根本就不渲染。任何人都可以向我解釋爲什麼這是?JTable與ScrollPane行爲不端

private static class GameHistoryPanel extends JPanel { 

     private DataModel model; 
     private JTable table; 
     private int currentRow; 
     private int currentColumn; 
     private final Dimension HISTORY_PANEL_DIMENSION = new Dimension(190,460); 


     public GameHistoryPanel() { 
      this.setLayout(new BorderLayout()); 
      this.model = new DataModel(); 
      this.table = new JTable(model); 
      this.add(table.getTableHeader(), BorderLayout.NORTH); 
      this.add(table, BorderLayout.CENTER); 
//   JScrollPane scrollPane = new JScrollPane(); 
//   scrollPane.setViewportView(table); 
//   this.add(scrollPane); 
      setPreferredSize(HISTORY_PANEL_DIMENSION); 
      this.currentRow = 0; 
      this.currentColumn = 0; 
     } 

     public void increment(Board board, Move move) { 
      model.setValueAt(move, currentRow, currentColumn); 
      if(board.currentPlayer().getAlliance() == Alliance.WHITE) { 
       currentColumn++; 
      } else if (board.currentPlayer().getAlliance() == Alliance.BLACK) { 
       currentRow++; 
       currentColumn = 0; 
      } 
      validate(); 
      repaint(); 
     } 
    } 
+0

我認爲通過回答(@trashgod),你的問題和代碼的一切重要的基礎在那裏, – mKorbel

回答

2

看起來您正在使用JTable作爲TableModel的視圖,其中每個單元格都以兩種狀態之一存在。對單元的可見變化應該導致只有從模型的變化,這可以在準備單元的renderer時進行檢查。特別是,調用方法validate()repaint()應該是而不是是必需的。他們的存在表明你在沒有模型知識的情況下改變了觀點,這可以解釋看到的異常。

1

嘗試

JScrollPane scrollPane = new JScrollPane(table); 
this.add(scrollPane); 
+0

這似乎並沒有伎倆。 –

+0

@AmirAfghani,嘗試在JScrollPane上設置首選大小 –

+1

@Amir阿富汗尼然後發佈[SSCCE](http://sscce.org/),exaclty展示了您的問題,簡短,可運行,可編譯,僅僅是關於JFrame,JSCrollPane和JTable – mKorbel

1

這可能說明明顯,但要記住,你只能添加一個JComponent到容器一次

this.setLayout(new BorderLayout()); 
this.model = new DataModel(); 
this.table = new JTable(model); 

要麼你

this.add(table, BorderLayout.CENTER); 
// note that table-headers should not be added explicitly 
// commented out: this.add(table.getTableHeader(), BorderLayout.NORTH); 

,或者你

JScrollPane scrollPane = new JScrollPane(table); 
this.add(scrollPane); 

而是試圖做既會造成問題。

我推薦使用Swingx的JXTable,如果可能的話。更加靈活,並且可以立即使用列分類和隱藏/重新排序。

+0

感謝您的答覆 - 但事實上這是顯而易見的。前者的作品,後者沒有。爲什麼不能明確添加表頭? –