SinTek Solutions
SinTek Solutions

Reputation: 115

java: Simulate keypress and hold while mouse hovers

I am trying to simulate a keypress and hold (in java) while the mouse is on top of a button. The keypress should only stop when the mouse is no longer over the button. I have the keypress working but not to keep it pressed. What is the best way to do this? I tried never-ending loops but then it does not stop when the mouse exits (obviously).

Here is my somewhat working code:

    buttonSD = new JButton("S+D");
    buttonSD.addMouseListener(new MouseAdapter(){
        public void mouseEntered(MouseEvent e){
            CoordsLabel.setText("Bottom Right");
                currentBtn.keyPress(KeyEvent.VK_S);
                currentBtn2.keyPress(KeyEvent.VK_D);
        }

        public void mouseExited(MouseEvent e){
            currentBtn.keyRelease(KeyEvent.VK_S);
            currentBtn2.keyRelease(KeyEvent.VK_S);
        }
    });
    c.weightx = .25;
    c.weighty = .25;
    c.gridx = 2;
    c.gridy = 2;
    gridbag.setConstraints(buttonSD, c);
    controlFrame.add(buttonSD);

    try{
        currentBtn = new Robot();
        currentBtn2 = new Robot();
    } catch (AWTException e){
        e.printStackTrace();
    }

Thanks in advance!

Upvotes: 0

Views: 90

Answers (2)

camickr
camickr

Reputation: 324137

So, he can use WASD with just a mouse over.

So then what you probably want to do is start a Swing Timer on the mouseEntered event and then stop the Timer on a mouseExited event.

When the timer fires you would then just invoke the doClick() method of the button.

Read the section from the Swing tutorial on How to Use Swing Timer for more information and working examples.

You can also check out: Update a Label with a Swing Timer for a simpler example.

Upvotes: 1

noumenal
noumenal

Reputation: 1237

A MouseEvent e is fired. To simulate a key hold, send the keyPress only once by adding a variable called toggle to represent the hold state and add a guardian clause to each function:

bool toggle = 0;

public void mouseEntered(MouseEvent e){
        if (toggle == 0) {
            CoordsLabel.setText("Bottom Right");
            currentBtn.keyPress(KeyEvent.VK_S);
            currentBtn2.keyPress(KeyEvent.VK_D);
            toggle = 1;
        }
    }


public void mouseExited(MouseEvent e){
        if (toggle == 1) {
            CoordsLabel.setText("RELEASED");
            currentBtn.keyRelease(KeyEvent.VK_S);
            currentBtn2.keyRelease(KeyEvent.VK_S);
        } else {
            CoordsLabel.setText("Nope");
        }
    }

Upvotes: 0

Related Questions