How to get mouse over event in `Java Swing`

I have JPanel

a few components in it - a few JLabels

, JTextBoxes

, JComboBoxes

, JCheckBoxes

, etc.

I want to display a help popup if the user hovers over these components for say 3 seconds.

So far I have added MouseListener

to one of my Components and it displays the required popup and help. However, I can't seem to achieve this after a 3 second delay. As soon as the user moves the mouse to this area of ​​the component, a popup will appear. This is very annoying as the components are practically unusable. I tried using MouseMotionListener

and had the following code in the method mouseMoved(MouseEvent e)

. Gives the same effect.

Any suggestion on how I can achieve the mouse hover effect - display the popup only after a 3 second delay?

Example code: (mouse input 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");
        }
    }

}

      

+3


source to share


1 answer


Use Timer

in mouseEntered()

. Here's a working example:



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);
    }
}

      

+4


source







All Articles