我正在尝试创建一个可单击的列标题(这样无论何时单击一个方法都会调用该方法).
链接到图像(因为我还没有10个声誉)http://img156.imageshack.us/img156/5764/clickablecolumn.png
列标题为红色矩形.
到目前为止我所做的就是响应任何列字段(例如James,Benny-G和Rokas的字段)被按下.
代码:
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);
标签:java,header,swing,jtable
来源: https://codeday.me/bug/20190713/1451848.html