gpt4 book ai didi

java - 在 Swing 中未按下鼠标的组件上监听鼠标释放事件

转载 作者:行者123 更新时间:2023-11-30 07:09:47 27 4
gpt4 key购买 nike

是否可以在未按下鼠标的组件上监听鼠标释放事件?

我知道当鼠标被释放时 MouseListener.mouseReleased() 会在鼠标按下时在该组件的监听器上调用,即使光标位于其他组件上方也是如此。

如何通知组件或其监听器鼠标悬停在其上并已释放?

最佳答案

如果您将 MouseListener 添加到包含您感兴趣的组件的容器中,您可以找出鼠标在按下或拖动时悬停在哪个组件上。例如,在下面的代码中,我将我的 MouseAdapter(MouseListener、MouseMotionListener 和 MouseWheelListener 的组合)添加到包含的 JPanel 中,在获取鼠标事件在容器上的位置后,我调用 getComponentAt(Point p ) 在我的容器上获取​​鼠标悬停的子组件:

import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class TestMouseRelease extends JPanel {
private String[] panelNames = { "Panel A", "Panel B" };

public TestMouseRelease() {
setLayout(new GridLayout(1, 0));
MouseAdapter mAdapter = new MyMouseAdapter();

addMouseListener(mAdapter);
addMouseMotionListener(mAdapter);

for (String panelName : panelNames) {
JPanel panel = new JPanel();
panel.setName(panelName);
// panel.addMouseListener(mAdapter);
// panel.addMouseMotionListener(mAdapter);
panel.setBorder(BorderFactory.createTitledBorder(panelName));
panel.add(Box.createRigidArea(new Dimension(300, 300)));
add(panel);
}
}

private class MyMouseAdapter extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
displayInfo(e, "mousePressed");
}

@Override
public void mouseReleased(MouseEvent e) {
displayInfo(e, "mouseReleased");
}

@Override
public void mouseDragged(MouseEvent e) {
displayInfo(e, "mouseDragged");
}

private void displayInfo(MouseEvent e, String info) {
JComponent comp = (JComponent) e.getSource();
Component childComp = comp.getComponentAt(e.getPoint());
if (childComp != null) {
String name = childComp.getName();
System.out.println(name + ": " + info);
}
}
}

private static void createAndShowGui() {
JFrame frame = new JFrame("TestMouseRelease");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TestMouseRelease());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

关于java - 在 Swing 中未按下鼠标的组件上监听鼠标释放事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22698435/

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