java - Updating a JLabel with a Static Integer -
so i'm new java, took class in highschool last year , want try , make own little 2d game im working on. have stats.java filled variables want stored, such cash, name, level, etc. right im trying add cash cash jlabel using button.
jbutton btnaddcash = new jbutton("add 10,000"); btnaddcash.addactionlistener(new actionlistener() { public void actionperformed(actionevent e) { stats.cash = (stats.cash + 5000); } }); jlabel lblcash = new jlabel("cash: " +stats.cash); lblcash.setforeground(color.white); lblcash.setbounds(10, 649, 162, 14); contentpane.add(lblcash); lblcash.setfont(new font("airbusmcdua", font.bold, 15)); jbutton debugbtn = new jbutton("");
any awesome!
your problem here @ (a) , (b)
jbutton btnaddcash = new jbutton("add 10,000"); btnaddcash.addactionlistener(new actionlistener() { public void actionperformed(actionevent e) { stats.cash = (stats.cash + 5000); // (a) } }); jlabel lblcash = new jlabel("cash: " +stats.cash); // (b)
understand when create jlabel holds present value of cash field , not hold reference field itself. important since updating cash field have no effect on jlabel's text. must explicitly change text:
btnaddcash.addactionlistener(new actionlistener() { public void actionperformed(actionevent e) { stats.cash = (stats.cash + 5000); lblcash.settext("cash: " +stats.cash); // ****** update text } });
other issues:
- again, avoid static unless have reason using this
- look model-view-controller design pattern , study it. type of structure want use.
- avoid absolute positioning of components (null layouts ,
setbounds
) lead frustration, grief , poor gui's. use layout managers - consider learning javafx instead of swing since javafx being supported actively oracle while swing not.
Comments
Post a Comment