Question

I have a frame, in this frame I have 10 labels.

If I click on label then it icon should be set to "zoldgomb.jpg", if I click a second time it should be set to "sargagomb.jpg".

This part is working, now my question is: How can it be written so that I don't have to write this part down ten times for each of the 10 labels (label name A1-A11)?

if (event.getSource()==A1) {

if (x==1) {
A1.setIcon(new ImageIcon("zoldgomb.jpg"));
x=2;
}else if (x==2) {
 A1.setIcon(new ImageIcon("sargagomb.jpg"));
 x=1;
}  }
Was it helpful?

Solution

event.getSource() return reference to your JLabel, you can use something like next:

    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;
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top