Reputation: 511
I have a JFrame with small squares set as background. Squares are pictures. Amount of squares depends on JFrame size, so I use ArrayList and I add JLabels to JFrame using:
for(int i = 0; i < squares.size(); i++){
add(squares.get(i));
}
I want to write a method so when mouse enters square it would change its color. I have implemented MouseListener. However this does not work(it works with normal JLabels):
ArrayList<JLabel> squares = new ArrayList<JLabel>();
. . .
@Override
public void mouseEntered(MouseEvent e) {
Object source = e.getSource();
if(source == squares){
System.out.println("AAA");
}
if(source == squares.get(0)){
System.out.println("BBB");
}
}
My question: How do I get element out of ArrayList, so I could set it equal to source and if its equal to source do something?
Upvotes: 0
Views: 274
Reputation: 324207
However this does not work(it works with normal JLabels):
This statement does not make sense. A JLabel is a JLabel. As long as you add the label to the frame it should work. The fact that you created an ArrayList as well doesn't affect how the label works on the frame.
Object source = e.getSource();
You already have the source, so all you need to do is cast it to a JLabel:
JLabel enteredLabel = (JLabel).getSource();
enteredLabel.doSomething(...)
Upvotes: 3