如何在`Java Swing`中获取鼠标悬停事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25393134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Mouse hover event in `Java Swing`
提问by TinyStrides
I have a JPanel
with multiple components in it - like a few JLabels
, JTextBoxes
, JComboBoxes
, JCheckBoxes
etc.
我有一个JPanel
由多个部分组成的它-就像一些JLabels
,JTextBoxes
,JComboBoxes
,JCheckBoxes
等。
I want to display a pop up help window if the user hovers over these components for say 3 secs.
如果用户将鼠标悬停在这些组件上 3 秒,我想显示一个弹出式帮助窗口。
So far I added a MouseListener
to one of my Components and it does display the required pop up and help. However I can't achieve it after 3 sec delay. As soon as the user moves the mouse to through that area of the component the pop up displays. This is very annoying as the components are almost unusable. I have tried using MouseMotionListener
and having the below code in mouseMoved(MouseEvent e)
method. Gives the same effect.
到目前为止,我MouseListener
在我的一个组件中添加了一个,它确实显示了所需的弹出窗口和帮助。但是我无法在 3 秒延迟后实现它。只要用户将鼠标移动到组件的该区域,就会显示弹出窗口。这很烦人,因为组件几乎无法使用。我曾尝试MouseMotionListener
在mouseMoved(MouseEvent e)
方法中使用并使用以下代码。产生相同的效果。
Any suggestion on how can I achieve the mouse hover effect - to display the pop up only after 3 sec delay?
关于如何实现鼠标悬停效果的任何建议 - 仅在 3 秒延迟后显示弹出窗口?
Sample Code:(Mouse Entered method)
示例代码:(鼠标输入方法)
private JTextField _textHost = new JTextField();
this._textHost().addMouseListener(this);
@Override
public void mouseEntered(MouseEvent e) {
if(e.getSource() == this._textHost())
{
int reply = JOptionPane.showConfirmDialog(this, "Do you want to see the related help document?", "Show Help?", JOptionPane.YES_NO_OPTION);
if(reply == JOptionPane.YES_OPTION)
{
//Opens a browser with appropriate link.
this.get_configPanel().get_GUIApp().openBrowser("http://google.com");
}
}
}
回答by whiskeyspider
Use a Timer
in mouseEntered()
. Here's a working example:
使用一个Timer
in mouseEntered()
。这是一个工作示例:
public class Test {
private JFrame frame;
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Test test = new Test();
test.createUI();
}
});
}
private void createUI() {
frame = new JFrame();
JLabel label = new JLabel("Test");
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent me) {
startTimer();
}
});
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
}
private void startTimer() {
TimerTask task = new TimerTask() {
@Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(frame, "Test");
}
});
}
};
Timer timer = new Timer(true);
timer.schedule(task, 3000);
}
}