jtable默认单击表头是没有什么反应的,对于使用过excel的人来说会很失望
要让单击表头就选中该列也很简单,直接上代码
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
public class ColumnSelectableJTable extends JTable {
public ColumnSelectableJTable (Object[][] items, Object[] headers) {
super (items, headers);
//设置列选择模式
setColumnSelectionAllowed (true);
setRowSelectionAllowed (false);
final JTableHeader header = getTableHeader();
//表头增加监听
header.addMouseListener (new MouseAdapter() {
public void mouseReleased (MouseEvent e) {
if (! e.isShiftDown())
clearSelection();
//获取点击的列索引
int pick = header.columnAtPoint(e.getPoint());
//设置选择模型
addColumnSelectionInterval (pick, pick);
}
});
}
}