gpt4 book ai didi

java - 当鼠标悬停在 JTable 上时滚动 JPanel

转载 作者:行者123 更新时间:2023-12-04 05:44:01 25 4
gpt4 key购买 nike

我有一个 JTable里面JPanel .我可以上下滚动 JPanel使用鼠标的滚轮,但是当我的鼠标悬停在 JTable 上时,我必须将它移出表格才能向上滚动 JPanel使用滚轮。有没有办法可以上下滚动 JPanel如果鼠标悬停在 JTable 上,则使用滚轮?

最佳答案

我在上面的评论中接受了 Xeon 的建议,并实现了一个鼠标滚轮监听器,将鼠标滚轮事件转发到父组件。请参阅下面的代码。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com