2010-02-23 73 views
71

我有以下代碼來實例化一個JTable:表中出現了正確數量的行和列,但沒有在列上標題的標誌。JTable將不會顯示列標題

public Panel1() 
{ 
    int nmbrRows; 

    setLayout(null); 
    setBackground(Color.magenta); 
    Vector colHdrs; 

    //create column headers 

    colHdrs = new Vector(10); 
    colHdrs.addElement(new String("Ticker")); 

    // more statements like the above to establish all col. titles  

    nmbrRows = 25; 
    DefaultTableModel tblModel = new DefaultTableModel(nmbrRows, colHdrs.size()); 
    tblModel.setColumnIdentifiers(colHdrs); 

    scrTbl = new JTable(tblModel); 
    scrTbl.setBounds(25, 50, 950, 600); 
    scrTbl.setBackground(Color.gray); 
    scrTbl.setRowHeight(23);  
    add(scrTbl); 

//rest of constructor 
... 

} 

這相較於其他表使代碼,我沒有看到任何缺失的步驟,但東西必須是不存在的。

回答

153

將您的JTable放入JScrollPane之內。試試這個:

add(new JScrollPane(scrTbl)); 
+5

我發現(和使用)此解決方案之前,但我很好奇,如果有人知道*爲什麼這個工程。 – 2010-02-23 19:19:11

+16

將表頭放入JScrollPane頂層組件(或頂層視圖或類似的東西被命名)當沒有頂層組件時,JTable顯示爲無頭。這是設計。 – OscarRyz 2010-02-23 19:43:42

+9

我找到了這個鏈接,它可能有助於解釋這個問題:http://blog.danieldee.com/2009/07/showing-jtable-header-without-using.html – 2010-02-23 20:11:35

19

這個答案和接受的答案之間的主要區別是使用setViewportView() instead of add()

如何使用Eclipse IDE把JTableJScrollPane

  1. 創建通過設計選項卡JScrollPane容器。
  2. 拉伸JScrollPane到所需的大小(適用於絕對佈局)。
  3. JScrollPane(視區區域)頂部拖放JTable組件。

在結構>組件中,table應該是scrollPane的子項。 enter image description here

生成的代碼會是這樣的:

JScrollPane scrollPane = new JScrollPane(); 
... 

JTable table = new JTable(); 
scrollPane.setViewportView(table); 
6

正如在以前的答案的「正常」的方法是將其添加到JScrollPane中說,但有時你不希望它滾動(不要問我什麼時候:))。然後你可以自己添加TableHeader。就像這樣:

JPanel tablePanel = new JPanel(new BorderLayout()); 
JTable table = new JTable(); 
tablePanel.add(table, BorderLayout.CENTER); 
tablePanel.add(table.getTableHeader(), BorderLayout.NORTH); 
-1
public table2() { 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setBounds(100, 100, 485, 218); 
    setTitle("jtable"); 
    getContentPane().setLayout(null); 

    String data[][] = { { "Row1/1", "Row1/2", "Row1/3" }, 
      { "Row2/1", "Row2/2", "Row2/3" }, 
      { "Row3/1", "Row3/2", "Row3/3" }, 
      { "Row4/1", "Row4/2", "Row4/3" }, }; 

    String header[] = { "Column 1", "Column 2", "Column 3" }; 

    // Table 
    JTable table = new JTable(data,header); 


    // ScrollPane 
    JScrollPane scrollPane = new JScrollPane(table); 
    scrollPane.setBounds(36, 37, 407, 79); 
    getContentPane().add(scrollPane); 

    } 

}

試試這個!

+1

'getContentPane()。add(table);'在這裏沒有意義。除此之外:與現有答案相比,此答案不會添加任何內容。 – Marco13 2017-06-17 11:33:04

+0

@chaithra_a你應該提供更多的描述爲什麼你這樣做。 – aircraft 2017-06-18 02:42:55