hudi
hudi

Reputation: 16555

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?

Upvotes: 0

Views: 1084

Answers (3)

mKorbel
mKorbel

Reputation: 109823

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

JTextComponents are Focusable, look for FocusListener

Upvotes: 2

Philipp Reichart
Philipp Reichart

Reputation: 20961

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().

Upvotes: 1

Andrew Thompson
Andrew Thompson

Reputation: 168845

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.

Upvotes: 2

Related Questions