java - How do I change the image on a JButton when clicked? -


    jbutton lunarbutton = new jbutton(new imageicon("assets/buttons/moon.png"));     lunarbutton.setactioncommand("switch");     c.gridwidth=1;     c.gridy = 0;     searcharea.add(lunarbutton, c); 

.

public void actionperformed(actionevent ev) {     int count = 1;     string action = ev.getactioncommand();      if("switch".equals(action))     {                    imageicon sun = new imageicon("assets/sun.png");         imageicon moon = new imageicon("assets/moon.png");          changelunar();         count++;         if (count % 2 == 0)         {              lunarbutton.seticon(sun);         }         else         {              lunarbutton.seticon(moon);         } 

i have code implemented, eclipse tells me "lunarbutton cannot resolved", not able see lunarbutton variable in init() method? missing here?

your lunarbutton may declared locally, perhaps in init method.

one solution: declare instance field in class, not in init method.

solution two: don't worry variable. jbutton object actionevent parameter's getsource() method. cast object returned jbutton, , call whatever methods you'd on it.

for example:

if("switch".equals(action)) {                // imageicon sun = new imageicon("assets/sun.png");     // imageicon moon = new imageicon("assets/moon.png");      jbutton btn = (jbutton) ae.getsource();      changelunar();     count++;     if (count % 2 == 0)     {          btn.seticon(sun);     }     else     {          btn.seticon(moon);     } 

as aside: don't want re-load images disk each time button pushed. instead read images in once, perhaps in constructor, stuff them imageicon field, , use field when needed.


Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -