Java Swing - JTable 中的多个列标题?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3320278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Swing - Multiple column headers in a JTable?
提问by Juan Diego
Is there any way to create multiple column headers in a JTable? I mean, normally there is only one row, but I need two of them with the same format (headerlike), and combine some cells of one of those headers.
有没有办法在一个中创建多个列标题JTable?我的意思是,通常只有一行,但我需要其中两个具有相同格式(标题),并组合这些标题之一的一些单元格。
I need something like this:
我需要这样的东西:
Header0 | Header123 | Header4 Header0 | Header1 | Header2 | Header3 | Header4
Is there any way?
有什么办法吗?
回答by SalutonMondo
Nick Meyer thanks for kindly reply, while the content in your address is a little out of date. i run it with jre 1.7 and it didn't works as expected but it can be altered to work correct. the alter i made are as follow
Nick Meyer 感谢您的回复,但您地址中的内容有点过时。我用 jre 1.7 运行它,但它没有按预期工作,但可以对其进行更改以使其正常工作。我所做的改变如下
/*
* add these code in GroupableTableHeader
*/
public void updateUI(){
// setUI(this.getUI());
TableCellRenderer renderer = getDefaultRenderer();
if (renderer instanceof Component) {
SwingUtilities.updateComponentTreeUI((Component)renderer);
}
}
/*
* add these code in GroupableTableHeaderUI in 2 places, you must know where
*/
if (renderer == null) {
renderer = header.getDefaultRenderer();
}
/*
* change the getSize method in ColumnGroup
*/
public Dimension getSize(JTable table) {
Component comp = renderer.getTableCellRendererComponent(
table, getHeaderValue(), false, false,-1, -1);
int height = comp.getPreferredSize().height;
int width = 0;
Enumeration en = v.elements();
while (en.hasMoreElements()) {
Object obj = en.nextElement();
if (obj instanceof TableColumn) {
TableColumn aColumn = (TableColumn)obj;
width += aColumn.getWidth();
// width += margin;
} else {
width += ((ColumnGroup)obj).getSize(table).width;
}
}
return new Dimension(width, height);
}
and the finally results.

和最后的结果。

回答by camickr
The Groupable Headerexample is some old code that might be able to help you.
该可分组报头的例子是一些旧的代码,也许能帮助你。
回答by rachvela
you can extend BasicTableHeaderUIand write your own implementation of paint method, in which you can draw any type of header.
after this change default header UI with following command table.getTableHeader().setUI(MyTableHeaderUI)
您可以扩展BasicTableHeaderUI和编写自己的paint方法实现,您可以在其中绘制任何类型的标题。使用以下命令更改默认标题 UI 后table.getTableHeader().setUI(MyTableHeaderUI)

