is there a way to check if the button we get from clicking (mouseClicked) is the same as a button that exists in a array of buttons? I've used both (==) and equals() but neither works.
i'm new to java, please take that in mind.
is there a way to check if the button we get from clicking (mouseClicked) is the same as a button that exists in a array of buttons? I've used both (==) and equals() but neither works.
i'm new to java, please take that in mind.
==
and equals()
have different functions:
==
==
becomes true if the two references of objects point to the same object, like this:
Object a = new Object();
Object b = a;
System.out.println(a == b);
// prints true because a referres to the same onject as b
equals()
equals()
returns true if the objects are equal, meaning not necessarily the same object. It instead checks whether all fields/properties are equal. It's implementation depends on the class.
One should use ActionListener
not MouseListener
to handle button clicks. When you do it you may access source of the click this way:
ActionListener al = e -> {
JButton button = (JButton) e.getSource();
//search your array here
};
button.addActionListener(al);
Then just go through your array and compare references by ==
operator. Also I suggest to use a Collection
instead of an array and use Collection.contains(T t)
method.