user13934566
user13934566

Reputation: 13

How to see how long a JButton is held down for using a MouseListener

I have a simple class:

public class MyButton extends JToggleButton {
    public MyButton() {
        super();
        this.addMouseListener(new MouseAdapter() {
            public mousePressed(MouseEvent event) {
                // See if it has been pressed for two seconds here
            }
        }
    });
}

I want to simply print "Hello World!" after the user has pressed and held for two seconds.

Upvotes: 0

Views: 40

Answers (1)

George Z.
George Z.

Reputation: 6808

You can achieve it with a Swing Timer that starts on mousePressed and will fire after X seconds, but stops onMouseReleased.

Consider this class:

public class ClickHoldMouseListener extends MouseAdapter {
        private Timer fireTimer;
        private MouseEvent lastEvent;

        public ClickHoldMouseListener(int holdTime, Consumer<MouseEvent> eventConsumer) {
            fireTimer = new Timer(holdTime, e -> eventConsumer.accept(lastEvent));
            fireTimer.setRepeats(false);
        }

        @Override
        public void mousePressed(MouseEvent e) {
            lastEvent = e;
            fireTimer.restart();
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            fireTimer.stop();
        }
    }

Now, you can add it to your button:

JButton button = new JButton("button");
button.addMouseListener(new ClickHoldMouseListener(2000, (event) -> {
    System.out.println("Mouse click was hold for 2seconds.");
}));

Note that the injected event is the mouse event from mousePressed method. You can change the consumer to a Runnable in order to ignore the event, or a Consumer<ActionEvent> to catch the event of the timer.

Upvotes: 1

Related Questions