JTable可点击列标题 [英] JTable clickable column header
问题描述
我正在尝试创建一个可点击的列标题(以便每次点击时调用一个方法)。
链接到图片(因为我没有10个声望) http://img156.imageshack.us/img156/5764/clickablecolumn.png
列标题为红色矩形。
到目前为止,我所做的只是在任何列字段(例如James,Benny-G和Rokas的列字段)被按下时做出响应。
代码:
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:
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
表示:
You want to add a mouse listener to the table header, which is represented by 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);
这篇关于JTable可点击列标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!