2012-06-10 35 views
0

我有一個JPanel,添加了JScrollPane(請參見下面的類)。我添加了一個JTextField來驗證一切正常(而不是JScrollPane)並且文本字段已添加到Panel中。當我嘗試添加我的JScrollPane時,沒有任何東西(白色背景)顯示。我該如何解決這個問題?Java - 帶JTable的JScrollPane未顯示

protected JPanel createContentPanel() { 
    JPanel panel = new JPanel(); 
    panel.setLayout(new BorderLayout()); 

    final String[] columnNames = { "Test1", "Test2", "Test3" }; 
    final String[][] data = { 
      { "foo1", "foo2", "foo3" }, 
      { "bar1", "bar2", "bar3" }, 
      { "bar1", "bar2", "bar3" }, 
      { "bar1", "bar2", "bar3" }, 
      { "bar1", "bar2", "bar3" }, 
      { "bar1", "bar2", "bar3" }, 
      { "bar1", "bar2", "bar3" }, 
      { "bar1", "bar2", "bar3" } 
    }; 

    ScrollableTable scrollableTablePane = new ScrollableTable(data, columnNames); 
    panel.add(scrollableTablePane, BorderLayout.CENTER); 
    return panel; 
} 


public class ScrollableTable extends JScrollPane { 

    public ScrollableTable(String[][] aData, String[] aColumnNames) { 
     super(); 

     TableModel model = getTableModel(aData, aColumnNames); 
     JTable overviewTable = new JTable(model); 
     overviewTable.setGridColor(new Color(240, 240, 240)); 
     TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model); 
     overviewTable.setRowSorter(sorter); 

     this.add(overviewTable); 
    } 

    private TableModel getTableModel(String[][] aData, String[] aColumnNames) { 
     TableModel model = new DefaultTableModel(aData, aColumnNames) { 
      public Class<?> getColumnClass(int column) { 
       return getValueAt(0, column).getClass(); 
      } 
     }; 
     return model; 
    } 
} 

回答

6

要設置JScrollPane的顯示組件,請使用JScrollPane#setViewportView(Component)而不是添加(組件)。

public ScrollableTable(String[][] aData, String[] aColumnNames) { 
    super(); 

    TableModel model = getTableModel(aData, aColumnNames); 
    JTable overviewTable = new JTable(model); 
    overviewTable.setGridColor(new Color(240, 240, 240)); 
    TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model); 
    overviewTable.setRowSorter(sorter); 

    this.setViewportView(overviewTable); 
} 
+0

這是有效的。非常感謝! :) –