简体   繁体   中英

Change value when mouse is clicked

I have JTextfield . Now I want to change value when in this component is mouse clicked. For example: score (2 big JTextField ) and when I click to one of these field it increase the value from 0:0 to 1:0.

Should I implement MouseListener or there is some easy way how I can do this? In mouse listener I need override just one method mouseClick and other method will be empty.

And another question: when should I implement MouseListener ? e.getButton() return always 1 for left button and 3 for right button?

Should I implement MouseListener or there is some easy way how I can do this? In mouse listner I need override just one method mouseClick and other method will be empty.

Use a MouseAdapter .

An abstract adapter class for receiving mouse events. The methods in this class are empty. .. Extend this class to create a MouseEvent (including drag and motion events) or/and MouseWheelEvent listener and override the methods for the events of interest.

Now I want to change value when in this component is mouse clicked

JTextComponents是Focusable的,请查找FocusListener

Implementing MouseListener on your class is one way to do it, but if you just want to react to clicks, it's easier to use an anonymous class extending MouseAdapter

textField.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
        // do your thing here
    }
});

As for the second question, the API documentation quite nicely documents the return values of MouseEvent.getButton() .

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