JavaSwingJTable点击表头选中和取消选中列
在JTable中单击表头是不会⾃动选中列的,也没有接⼝可以直接在JTable中获取到表头的点击事件,只能通过监听JTableHeader的⿏标事件来做出响应。
JTableHeader tableHeader = TableHeader();
tableHeader.setPreferredSize(new Width(), 35));
tableHeader.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
int choose = Point());
System.out.println("========="+choose);
table.addColumnSelectionInterval(choose, choose);
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
/
/ TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
});
实现效果如下:
但是这样选中后不能取消选中的状态,那么再做个取消选中的判断。
private int[] chooses;
chooses= new int[columnTitle.length];
for(int choose : chooses) {
chooses[choose] = -1;
}
JTableHeader tableHeader = TableHeader();
tableHeader.setPreferredSize(new Width(), 35));  tableHeader.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
int pick = Point());
if(chooses[choose] == -1 || chooses[choose] == 0) {
chooses[choose] = 1;
table.addColumnSelectionInterval(choose, choose);
} else {
chooses[choose] = -1;
}
}
@Override
public void mousePressed(MouseEvent e) {
/
/ TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
javaswing和javafx
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
});
搞定。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。