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 ... } 

与其他制表代码比较,我没有看到任何缺失的步骤,但一些必须缺席。

在此先感谢您的帮助。

将您的JTable放入JScrollPane 。 尝试这个:

 add(new JScrollPane(scrTbl)); 

这个答案和接受的答案之间的主要区别是使用setViewportView()而不是add()

如何使用Eclipse IDE在JScrollPane放置JTable

  1. 通过“devise”选项卡创buildJScrollPane容器。
  2. JScrollPane拉伸到所需的大小(适用于绝对布局)。
  3. JScrollPane (Viewport区域)的顶部拖放JTable组件。

在Structure> Components中, table应该是scrollPane的子scrollPane在这里输入图像说明

生成的代码是这样的:

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

正如前面的回答所说,“正常”的方法是将其添加到JScrollPane,但有时你不希望它滚动(不要问我什么时候:))。 然后你可以自己添加TableHeader。 喜欢这个:

 JPanel tablePanel = new JPanel(new BorderLayout()); JTable table = new JTable(); tablePanel.add(table, BorderLayout.CENTER); tablePanel.add(table.getTableHeader(), BorderLayout.NORTH); 
  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); } 

}

尝试这个!!