Search code examples
javajbuttonmouselistener

Mouse Listener implementation


I am learning Java and trying to implement a MouseListener for the first time. I have read the java doc MouseListener but my code doesnt work, as in nothing happens when i press the button. Here is a jbutton with a pressed and released event. Can someone explain where i have gone wrong?

JButton upButton_1 = new JButton("Up");
    upButton_1.addMouseListener(new MouseAdapter(){
        public void mousePressed(MouseEvent pevt) {
            upButtonPressPerformed(pevt);
        }
        public void mouseReleased(MouseEvent revt) {
            upButtonReleasePerformed(revt);
        }

        public synchronized void upButtonPressPerformed(
                MouseEvent pevt) {
            resultsTextArea.setText("Up Button Activated, String: " + downString);


                try{
                    //See Above comments for sending ASCII String
                    byte[] bytes = DatatypeConverter.parseHexBinary(upString);


                    TwoWaySerialComm.SerialWriter sw = new TwoWaySerialComm.SerialWriter(
                            twoWaySerCom.serialPort.getOutputStream());

                sw.out.write(bytes);

            } catch (IOException e) {

                e.printStackTrace();
            }
        }
        public synchronized void upButtonReleasePerformed(
        MouseEvent revt) {
        resultsTextArea.setText("Up Button released, String: " + downString);


            try{
                //See Above comments for sending ASCII String
                byte[] bytes = DatatypeConverter.parseHexBinary(upString);


                TwoWaySerialComm.SerialWriter sw = new TwoWaySerialComm.SerialWriter(
                        twoWaySerCom.serialPort.getOutputStream());

            sw.out.write(bytes);

        } catch (IOException e) {

            e.printStackTrace();
        }
    }
    });

Solution

  • ActionListener is what you are looking for if you want to work with buttons.

    JButton button = new JButton("SomeButton");
    button.addActionListener(this);
    
    void ActionPerformed(ActionEvent e) {
        if(e.getSource() == button) {
            // do whatever you want if button is clicked
        }
    }
    

    Or you can use anonymous inner class:

    button.addActionListener(new ActionListener() { 
        public void actionPerformed(ActionEvent e) {          
            //do whatever you want
        } 
    });
    
    //or the Java8 version
    button.addActionListener((e) -> {
        //do whatever you want
    });
    

    Whit MouseListener you can listen to events like: MouseClicked, MouseEntered, MouseExited, MousePresse, MouseReleased. You could use these, but for button click its more logical to listen to your buttons not your mouse.