2012-12-05 66 views
2

我在JPanel中放置JTable,但是當我顯示時,我看到表格內容但看不到列名稱。我沒有得到列的名稱

public class Neww extends JPanel 
{ 
    Connection conn = null; 
    Statement st; 
    DefaultTableModel model = new DefaultTableModel(new Object[][] { 
     { " ", " " }, 
     { " ", " " }, 
     { " ", " " }, 
     { " ", " " }, 
     { " ", " " }, 
     { " ", " " } 
    }, new Object[] { 
     "ItemName", 
     "No of items" 
    }); 

    JTable table = new JTable(model); 
    TableColumn ItemName = table.getColumnModel().getColumn(0); 
    JComboBox comboBox = new JComboBox(); 
    Neww() 
    { 
     this.setLayout(new FlowLayout(FlowLayout.CENTER)); 
     this.add(table); 

     comboBox.addItem("Spoon"); 
     comboBox.addItem("Plate"); 
     comboBox.addItem("Mixer"); 
     comboBox.addItem("Glass"); 
     ItemName.setCellEditor(new DefaultCellEditor(comboBox)); 
    } 
} 

回答

3

有兩種方式

  • (正確的方法)必須把JTableJScrollPane,則JTableHeader可見

  • JTable(其他城市JPanel小號LayoutManager得到JTableHeaderBorderLayout)並將其放入NORTH areaJPanel

+0

+1打我吧 –

2

1)將您的JTable包裝在JScrollPane之內。就像這樣:

JTable table=...; 

JPanel container = new JPanel(); 

JScrollPane jsp=new JScrollPane(table); 

container.add(jsp); 

2)使用getTableHeader(),並添加需要的地方(通常是北方雖然定位):

... 

JTableHeader header = table.getTableHeader(); 

JPanel container = new JPanel(new BorderLayout()); 

// Add header at NORTH position 
container.add(header, BorderLayout.NORTH); 

//Add table below header 
container.add(table, BorderLayout.CENTER); 
1

下面的語句在你的代碼中創建的問題。

this.add(table); 

添加表時使用滾動窗格。

add(new JScrollPane(table)); 

我們爲什麼要用JScrollPane

如在本comment.

表頭它放入JScrollPane的塔頂成分(或頂部 視圖或類似的東西被命名)表示由@OscarRyz當沒有塔頂成分 JTable的出現無頭。這是設計。

編輯:也期待這個answer瞭解更多詳情。

相關問題