java JTable 可点击的列标题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4615741/
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
JTable clickable column header
提问by shookees
I am trying to make a clickable column header (so that a method would be called whenever one's clicked).
link to image (since I don't have 10 reputation yet) http://img156.imageshack.us/img156/5764/clickablecolumn.png
The column header is in red rectangle.
What I've done so far is responding whenever any column field (such as the one with James, Benny-G and Rokas) is pressed.
The code:
我正在尝试制作一个可点击的列标题(以便在点击时调用一个方法)。
图像链接(因为我还没有 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
}
回答by sjr
You want to add a mouse listener to the table header, which is represented by JTableHeader
:
您想向表头添加一个鼠标侦听器,它由 表示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);