Materno
Materno

Reputation: 353

GWT hold mouse button

I'm working with GWT and want to do an action when the user holds the left mouse button on a GWT button. But I can't find the right event handler or another solution for that problem.

Is there a way in GWT to klick on a button, hold the mouse button and do the same action again and again till the mouse button is released?

Button scrollUpBtn = new Button("Top");
    scrollUpBtn.setWidth("66px");
    scrollUpBtn.addMouseDownHandler(new MouseDownHandler() {
        @Override
        public void onMouseDown(MouseDownEvent event) {
            //handCards.setVerticalScrollPosition(handCards.getVerticalScrollPosition() - 10);
            mouseUp = true;
        }
    });

    scrollUpBtn.addMouseUpHandler(new MouseUpHandler() {
        @Override
        public void onMouseUp(MouseUpEvent event) {
            mouseUp = false;
        }
    });

    scrollUpBtn.addKeyDownHandler(new KeyDownHandler() {
        @Override
        public void onKeyDown(KeyDownEvent event) {
            if (mouseUp == true) {
                handCards.setVerticalScrollPosition(handCards.getVerticalScrollPosition() - 10);
            }
        }
    });

Upvotes: 0

Views: 1398

Answers (2)

filip-fku
filip-fku

Reputation: 3265

Step 3 in Andrei's answer assumes that the KeyDownEvent will keep firing. I'm not sure if that's so..

An alternative would be to use the Down & Up handlers to start/stop a repeating timer which carries out your action. You can then set the repeat interval based on how often you want your action to be carried out. Remember that this runs as single threaded JavaScript, so if you carry out lengthy processing things will slow down and the scheduled intervals will not be on time.

    Button btn= new Button("Button");
    final Timer actionTimer = new Timer() {
           @Override
           public void run() {
                // Your action here
                System.out.println("Doing something!");
           }
    };
    btn.addMouseDownHandler(new MouseDownHandler() {
        @Override
        public void onMouseDown(MouseDownEvent event) {
             // Choose the appropriate delay
             actionTimer.scheduleRepeating(1000); 
        }
    });

    btn.addMouseUpHandler(new MouseUpHandler() {
        @Override
        public void onMouseUp(MouseUpEvent event) {
            actionTimer.cancel();
        }
    });

Upvotes: 1

Andrei Volgin
Andrei Volgin

Reputation: 41089

  1. Add MouseDownHandler to your widget. When it fires, it should set a flag to true, e.g. mouseDown = true;

  2. Add MouseUpHandler to your widget. When it fires, it should set a flag to false, e.g. mouseDown = false;

  3. Add KeyDownHandler to your widget. When if fires, check if flag is true - then do something. If flag is false, don't do it.

Upvotes: 0

Related Questions