JTable可点击列标题
问题描述:
我正在尝试制作可点击的列标题(以便每当点击时调用方法)。
链接到图像(因为我还没有10声望)http://img156.imageshack.us/img156/5764/clickablecolumn.png
列标题是红色的矩形。
到目前为止,我所做的只是在任何列字段(例如James,Benny-G和Rokas的列字段)被按下时做出响应。 代码:JTable可点击列标题
public void mouseClicked(MouseEvent e)
{
System.out.println("Mouse clicked");
TableColumnModel cModel = table.getColumnModel();//cModel - column model
int selColumn = cModel.getColumnIndexAtX(e.getX());//gets the selected column by clicked x coordinate
}
答
你想鼠标监听器添加到表头,其通过JTableHeader
表示:
JFrame frame = new JFrame();
frame.getContentPane().add(new JScrollPane(new JTable(4, 3) {
{
getTableHeader().addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
int index = convertColumnIndexToModel(columnAtPoint(mouseEvent.getPoint()));
if (index >= 0) {
System.out.println("Clicked on column " + index);
}
};
});
}
}));
frame.pack();
frame.setVisible(true);