I have a JDialog
as a Popup which shows up for 3 seconds and dispose.
It comes up at cursor position and has to dispose only if the cursor exits the popup.
If the cursor entered the Popup the timer stops and start again on exit.
But my first idea with a dispose-Timer
that starts and stops via MouseListener
doesn't work with some JComponent
s, which causes a mouseExited()
.
My second idea will never start the Timer
public void mouseExited( MouseEvent e ) {
if(!Popup.this.getBounds().contains( e.getLocationOnScreen() )){
timer.start();
}
}
I don't want to add the Listener to every component in the popup.
Is there an easy way to do that.
Example:
public class Popup extends JDialog {
private static final long serialVersionUID = 1337L;
private final Timer timer = new Timer( 3000, new ActionListener() {
@Override
public void actionPerformed( ActionEvent e ) {
Popup.this.dispose();
System.exit( 0 );
}
});
public Popup() {
setBounds( 100, 100, 300, 300 );
addMouseListener( new PopupBehavior() );
getContentPane().setLayout( new BorderLayout() );
getContentPane().add( new JTextArea(), BorderLayout.NORTH );
getContentPane().add( new JSplitPane(0,new JPanel(), new JLabel("2")), BorderLayout.CENTER );
getContentPane().add( new JProgressBar(), BorderLayout.SOUTH );
getContentPane().add( new JLabel("west"), BorderLayout.WEST );
getContentPane().add( new JSpinner(), BorderLayout.EAST );
}
public static void main( String[] args ) {
SwingUtilities.invokeLater( new Runnable() {
@Override
public void run() {
new Popup().setVisible( true );
}
});
}
private class PopupBehavior extends MouseAdapter {
@Override
public void mouseEntered( MouseEvent e ) {
System.out.println("mouseEntered");
timer.stop();
}
@Override
public void mouseExited( MouseEvent e ) {
System.out.println("mouseExited");
timer.start();
}
}
}