JTable将不会显示列标题
问题描述:
我有以下代码来实例化一个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()
instead of add()
。
如何使用Eclipse IDE把JTable
在JScrollPane
:
- 创建通过设计选项卡
JScrollPane
容器。 - 拉伸
JScrollPane
到所需的大小(适用于绝对布局)。 - 在
JScrollPane
(视区区域)顶部拖放JTable
组件。
在结构>组件中,table
应该是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);
}
}
试试这个!
我发现(和使用)此解决方案之前,但我很好奇,如果有人知道*为什么这个工程。 – 2010-02-23 19:19:11
将表头放入JScrollPane顶层组件(或顶层视图或类似的东西被命名)当没有顶层组件时,JTable显示为无头。这是设计。 – OscarRyz 2010-02-23 19:43:42
我找到了这个链接,它可能有助于解释这个问题:http://blog.danieldee.com/2009/07/showing-jtable-header-without-using.html – 2010-02-23 20:11:35