我必须禁用右键单击JTableHeader,以便用户无法右键单击列标题并拖动以重新定位列。我们有任何诀窍吗?只需要提一下鼠标左键单击效果很好但是当用户使用RMB并拖动列时,移动该列并在释放鼠标时重新绘制其他列。
感谢任何帮助。
答案 0 :(得分:1)
使用右键触发列拖动/调整大小显然是IMO的错误。
一个糟糕的解决方法是挂钩由uidelegate安装的鼠标/动作/监听器,并静静地吃掉所有不是左按钮的事件。类似的事情(注意:这个包装监听器的更健壮的安装将在LAF切换后继续outlined in a recent answer):
public static class BugHook implements MouseListener, MouseMotionListener {
private JTableHeader header;
private MouseListener mouseDelegate;
private MouseMotionListener motionDelegate;
public BugHook(JTableHeader header) {
this.header = header;
MouseListener[] ls = header.getMouseListeners();
for (int i = 0; i < ls.length; i++) {
header.removeMouseListener(ls[i]);
String name = ls[i].getClass().getName();
if (name.contains("TableHeaderUI")) {
this.mouseDelegate = ls[i];
ls[i] = this;
}
}
for (MouseListener l : ls) {
header.addMouseListener(l);
}
MouseMotionListener[] motionLs = header.getMouseMotionListeners();
for (int i = 0; i < motionLs.length; i++) {
header.removeMouseMotionListener(motionLs[i]);
String name = motionLs[i].getClass().getName();
if (name.contains("TableHeaderUI")) {
this.motionDelegate = motionLs[i];
motionLs[i] = this;
}
}
for (MouseMotionListener l : motionLs) {
header.addMouseMotionListener(l);
}
}
// methods delegation left buttons only
@Override
public void mousePressed(MouseEvent e) {
if (!SwingUtilities.isLeftMouseButton(e)) return;
mouseDelegate.mousePressed(e);
}
@Override
public void mouseDragged(MouseEvent e) {
if (!SwingUtilities.isLeftMouseButton(e)) return;
motionDelegate.mouseDragged(e);
}
@Override
public void mouseReleased(MouseEvent e) {
if (!SwingUtilities.isLeftMouseButton(e)) return;
mouseDelegate.mouseReleased(e);
}
/// ---------- methods delegating always
@Override
public void mouseClicked(MouseEvent e) {
mouseDelegate.mouseClicked(e);
}
@Override
public void mouseEntered(MouseEvent e) {
mouseDelegate.mouseEntered(e);
}
@Override
public void mouseExited(MouseEvent e) {
mouseDelegate.mouseExited(e);
}
@Override
public void mouseMoved(MouseEvent e) {
motionDelegate.mouseMoved(e);
}
}
答案 1 :(得分:0)
我尝试使用Java版本1.7.0_11和1.6.0_38并执行此操作:
table.getTableHeader().setReorderingAllowed(false);
会将列锁定到位。您是使用较旧的Java版本还是以其他方式禁用?