简体   繁体   中英

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;
    }
}
  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.

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