java - Changing Text Value of JLabel In Real Time -
i trying change text of jlabel (searchedstock) in real time. here code:
public void gamegui() { gridbagconstraints c = new gridbagconstraints(); c.fill = gridbagconstraints.horizontal; c.gridwidth = 2; jlabel welcome = new jlabel("welcome " + playername + "!"); welcome.setfont(new font("arial", 1, 30)); gamepanel.add(welcome, c); c.gridx = 0; c.gridy = 1; gamepanel.add(new jpanel(), c); c.gridwidth = 1; c.gridy = 2; gamepanel.add(new jlabel("symbol search:"), c); c.gridx = 1; final jtextfield symbolsearch = new jtextfield(10); gamepanel.add(symbolsearch, c); c.gridx = 0; c.gridy = 3; gamepanel.add(new jpanel(), c); c.gridx = 0; c.gridy = 4; c.gridwidth = 2; jbutton search = new jbutton("search"); search.addactionlistener(new actionlistener() { public void actionperformed(actionevent e){ stockvalue = double.tostring(getstocks(symbolsearch.gettext())); } }); gamepanel.add(search, c); c.gridx = 0; c.gridy = 5; gamepanel.add(new jpanel(), c); c.gridx = 0; c.gridy = 6; c.gridwidth = 2; jlabel searchedstock = new jlabel(stockvalue); gamepanel.add(searchedstock, c); add(gamepanel); }
how can change value in realtime pressing button because listener in inner class? not have direct access jlabel, cannot use settext(); , issue.
you have @ least 2 options...
option #1
make jlabel
final
, have before inner listener...
public void gamegui() { /*...*/ final jlabel searchedstock = new jlabel(stockvalue); jbutton search = new jbutton("search"); search.addactionlistener(new actionlistener() { public void actionperformed(actionevent e){ stockvalue = double.tostring(getstocks(symbolsearch.gettext())); searchedstock.settext(numberformat.getnumberinstance().format(stockvalue)); } }); gamepanel.add(search, c); c.gridx = 0; c.gridy = 5; gamepanel.add(new jpanel(), c); c.gridx = 0; c.gridy = 6; c.gridwidth = 2; gamepanel.add(searchedstock, c); add(gamepanel); }
option 2
make label class instance field...
private jlabel searchedstock; public void gamegui() { /*...*/ final jlabel searchedstock = new jlabel(stockvalue); jbutton search = new jbutton("search"); search.addactionlistener(new actionlistener() { public void actionperformed(actionevent e){ stockvalue = double.tostring(getstocks(symbolsearch.gettext())); searchedstock.settext(numberformat.getnumberinstance().format(stockvalue)); } }); gamepanel.add(search, c); c.gridx = 0; c.gridy = 5; gamepanel.add(new jpanel(), c); c.gridx = 0; c.gridy = 6; c.gridwidth = 2; searchedstock = new jlabel(stockvalue); gamepanel.add(searchedstock, c); add(gamepanel); }