鼠标侦听器实现

时间:2016-06-23 05:11:11

标签: java jbutton mouselistener

我正在学习Java并尝试首次实现MouseListener。我已经阅读了java doc MouseListener但我的代码不起作用,因为按下按钮时没有任何反应。这是一个按下并释放事件的jbutton。有人能解释我哪里出错吗?

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();
        }
    }
    });

1 个答案:

答案 0 :(得分:3)

如果您想使用按钮,

ActionListener就是您要寻找的。

JButton button = new JButton("SomeButton");
button.addActionListener(this);

void ActionPerformed(ActionEvent e) {
    if(e.getSource() == button) {
        // do whatever you want if button is clicked
    }
}

或者您可以使用匿名内部类:

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您可以收听以下事件: MouseClicked,MouseEntered,MouseExited,MousePresse,MouseReleased。 你可以使用这些,但是对于按钮点击它更合乎逻辑地听你的按钮而不是你的鼠标。