swing - Random Image in Java -
how make random image appear when click button? need add view images change when click button
class buttonlistener
:
public class buttonlistener implements actionlistener { private model mod; public buttonlistener(model _m){ mod = _m; } @override public void actionperformed(actionevent e) { int x = mod.random(); if (x == 1) { jlabel l1 = new jlabel(); jlabel l2 = new jlabel(); jlabel l3 = new jlabel(); l1.seticon(new imageicon ("images/green.png")); system.out.println("1"); } else if (x == 2) { jlabel l1 = new jlabel(); l1.seticon(new imageicon("images/purple.png")); system.out.println("2"); } else { jlabel l1 = new jlabel(); l1.seticon(new imageicon("images/red.png")); system.out.println("3"); } } }
class view
:
public class view { public view() { model _m = new model(); jframe f = new jframe("...."); jpanel p = new jpanel(new gridlayout(2, 3)); jlabel l1 = new jlabel(); jlabel d = new jlabel(); jlabel l2 = new jlabel(); jlabel l3 = new jlabel(); jbutton b = new jbutton("spin"); p.add(l2); p.add(l3); p.add(l1); p.add(d); p.add(b); b.addactionlistener(new buttonlistener(_m)); f.add(p); f.pack(); f.setvisible(true); f.setdefaultcloseoperation(jframe.exit_on_close); } }
class model
:
public class model { public model(){ } public int random(){ random rand = new random(); return rand.nextint(4); } }
your code appears trying create m-v-c program, , if so, model needs
- state (i.e., field or fields)
- ability accept , notify listeners of change when 1 of "bound" fields changes, view can notified, either directly (e.g., view has listener registered model) or indirectly (e.g., controller has listener registered model, , when notified -- controller -- changes view).
when i've done this, i've given model swingpropertychangesupport field methods allow other classes add , remove propertychangelisteners support object. bound fields, here field representing random int, has setter method, , within method, have support object notify listeners holds calling 1 of firepropertychange(...)
methods.
for example, please check out answer similar question here: using jfilechooser swing gui classes , listeners
Comments
Post a Comment