user3633989
user3633989

Reputation: 29

using Java mouseClicked event handler to change icons

I have tons of labels. My problem is that I don't know how to write that if i click label2, then set a new image on label2 but label1 doesnt change. labels are named like A1-A10. (I actually have 92 labels, so this is getting cumbersome.) Here's my code:

public void mouseClicked(MouseEvent event) {

    if (event.getSource()==A1 && (x==1)) {
        A1.setIcon(new ImageIcon("zoldgomb.jpg"));
        x=2;
    } else if(x==2) {
        A1.setIcon(new ImageIcon("sargagomb.jpg"));
        x=1;
    }
}

edit

ok, i solved it, thx everybody :)

if (event.getSource() instanceof JLabel) {
                if (x == 1) {
                    ((JLabel)event.getSource()).setIcon(new ImageIcon("zoldgomb.jpg"));
                    x = 2;
                } else if (x == 2) {
                    ((JLabel)event.getSource()).setIcon(new ImageIcon("sargagomb.jpg"));
                    x = 1;
    }
}

Upvotes: 1

Views: 426

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

  1. It sounds like you should be using either an array or ArrayList of JLabel.
  2. Variable names should all begin with a lower letter while class names with an upper case letter. Also you should avoid using trivial variable names such as b or s unless they are being used for trivial purposes such as the index of a for loop. Instead use names that have some meaning so that your code becomes self-commenting.
  3. You can identify which JLabel was pressed by calling getSource() on the MouseEvent objevct passed into your method. Your parameter is named event above.
  4. Then after testing which JLabel is pressed, call its setIcon(...) method.
  5. You're better off reading in your images once and saving them to a variable, and not re-reading them in on each mouse click.

Upvotes: 2

Related Questions