我在 JPanel
内有一个 JTable
。我可以使用鼠标滚轮上下滚动 JPanel
,但是当我的鼠标悬停在 JTable
上时,我必须将其移出表格才能向后滚动使用滚轮打开 JPanel
。如果鼠标悬停在 JTable
上,是否可以使用滚轮上下滚动 JPanel
?
最佳答案
我采纳了上面评论中至强的建议,并实现了一个鼠标滚轮监听器,它将鼠标滚轮事件转发到父组件。请参阅下面的代码。
public class CustomMouseWheelListener implements MouseWheelListener {
private JScrollBar bar;
private int previousValue = 0;
private JScrollPane parentScrollPane;
private JScrollPane customScrollPane;
/** @return The parent scroll pane, or null if there is no parent. */
private JScrollPane getParentScrollPane() {
if (this.parentScrollPane == null) {
Component parent = this.customScrollPane.getParent();
while (!(parent instanceof JScrollPane) && parent != null) {
parent = parent.getParent();
}
this.parentScrollPane = (JScrollPane) parent;
}
return this.parentScrollPane;
}
/**
* Creates a new CustomMouseWheelListener.
* @param customScrollPane The scroll pane to which this listener belongs.
*/
public CustomMouseWheelListener(JScrollPane customScrollPane) {
ValidationUtils.checkNull(customScrollPane);
this.customScrollPane = customScrollPane;
this.bar = this.customScrollPane.getVerticalScrollBar();
}
/** {@inheritDoc} */
@Override
public void mouseWheelMoved(MouseWheelEvent event) {
JScrollPane parent = getParentScrollPane();
if (parent != null) {
if (event.getWheelRotation() < 0) {
if (this.bar.getValue() == 0 && this.previousValue == 0) {
parent.dispatchEvent(cloneEvent(event));
}
}
else {
if (this.bar.getValue() == getMax() && this.previousValue == getMax()) {
parent.dispatchEvent(cloneEvent(event));
}
}
this.previousValue = this.bar.getValue();
}
else {
this.customScrollPane.removeMouseWheelListener(this);
}
}
/** @return The maximum value of the scrollbar. */
private int getMax() {
return this.bar.getMaximum() - this.bar.getVisibleAmount();
}
/**
* Copies the given MouseWheelEvent.
*
* @param event The MouseWheelEvent to copy.
* @return A copy of the mouse wheel event.
*/
private MouseWheelEvent cloneEvent(MouseWheelEvent event) {
return new MouseWheelEvent(getParentScrollPane(), event.getID(), event.getWhen(),
event.getModifiers(), 1, 1, event.getClickCount(), false, event.getScrollType(),
event.getScrollAmount(), event.getWheelRotation());
}
}
关于java - 当鼠标悬停在 JTable 上时滚动 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10924099/