2010-02-23 107 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