简体   繁体   中英

How to assign a method to a button when pressed or released with ActionListener in Java?

I am new to coding GUIs in Java and I am trying to just print a message on the terminal when a button is pressed and another one when it is released.

This is what I have for a regular button pressing.

 leftButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            System.out.println("Pressed");
        }
    });

I did this with the help of IntelliJ IDEA. I want to make the button send a message when pressed and a different thing when released.

You can just add a simple MouseAdapter , like this:

MouseAdapter ma = new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
        System.out.println("Pressed");
    }
    public void mouseReleased(MouseEvent e) {
        System.out.println("Released");
    }
};
leftButton.addMouseListener(ma);
frame.add(button);

This will detect when it is the mouse is pressed on the button or released on the button.

If you want, you can also add a mouseClicked() method, mouseExited() , mouseEntered() , mouseMoved() , and (many) more methods in your MouseAdapter . Check out this JavaDoc

Use custom class and use it

 leftButton.getModel().addChangeListener(new BtnCusttomListener());




 private class BtnCusttomListener implements ChangeListener {
        private boolean pressed = false;  // holds the last pressed state of the button

        @Override
        public void stateChanged(ChangeEvent e) {
            ButtonModel Buttonmodel = (ButtonModel) e.getSource();

            // if the current state differs from the previous state
            if (model.isPressed() != pressed) {
                String text = "Button pressed: " + model.isPressed() + "\n"; 
                textArea.append(text);
                pressed = model.isPressed();
            }
        }
    }

You can use a MouseListener instead:

leftButton.addMouseListener(new MouseListener() {
    @Override
    public void mouseClicked(MouseEvent e) {
        // The mouse button was pressed and released
    }

    @Override
    public void mousePressed(MouseEvent e) {
        // The mouse button was pressed
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // The mouse button was released
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        // The cursor entered the bounds of the button (i.e. hovering)
    }

    @Override
    public void mouseExited(MouseEvent e) {
        // The cursor exited the bounds of the button
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM