[英]How to get Mouse hover event in `Java Swing`
我有一個包含多個組件的JPanel
- 比如一些JLabels
, JTextBoxes
, JComboBoxes
, JCheckBoxes
等。
如果用戶將鼠標懸停在這些組件上3秒鍾,我想顯示一個彈出幫助窗口。
到目前為止,我在我的一個組件中添加了一個MouseListener
,它確實顯示了所需的彈出窗口和幫助。 但是在3秒延遲后我無法實現它。 一旦用戶將鼠標移動到組件的該區域,彈出窗口就會顯示。 這非常令人討厭,因為組件幾乎無法使用。 我嘗試過使用MouseMotionListener
並在mouseMoved(MouseEvent e)
方法中使用以下代碼。 產生同樣的效果。
有關如何實現鼠標懸停效果的任何建議 - 僅在延遲3秒后顯示彈出窗口?
示例代碼:(鼠標輸入方法)
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");
}
}
}
在mouseEntered()
使用Timer
。 這是一個有效的例子:
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.