java - How can I access this variable inside of an ActionListener? -
public class daysalivegui { public static void main(string[] args) { eventqueue.invokelater(new runnable() { public void run() { try { daysalivegui window = new daysalivegui(); window.frame.setvisible(true); } catch (exception e) { e.printstacktrace(); } } }); } public daysalivegui() { initialize(); } private void initialize() { jbutton jbutton_calculate = new jbutton("calculate"); jbutton_calculate.addactionlistener(new actionlistener() { public void actionperformed (actionevent arg0) { int idaybirth = integer.parseint(jtextfield_dobday.gettext()); int imonthbirth = integer.parseint(jtextfield_dobmonth.gettext()); int iyearbirth = integer.parseint(jtextfield_dobyear.gettext()); int idaycurrent = integer.parseint(jtextfield_cdday.gettext()); int imonthcurrent = integer.parseint(jtextfield_cdmonth.gettext()); int iyearcurrent = integer.parseint(jtextfield_cdyear.gettext()); double idaysalive; calendar cabirthdate = new gregoriancalendar(iyearbirth, imonthbirth - 1, idaybirth); calendar cacurrentdate = new gregoriancalendar(iyearcurrent, imonthcurrent - 1, idaycurrent); idaysalive = cacurrentdate.gettimeinmillis() - cabirthdate.gettimeinmillis(); idaysalive = idaysalive / (24 * 60 * 60 * 1000) + 1; } }); jbutton_calculate.setfont(new font("calibri", font.bold, 15)); jbutton_calculate.setbounds(180, 205, 103, 23); frame.getcontentpane().add(jbutton_calculate); /* here error: idaysalive cannot resolved variable*/ jlabel lbldaysalive = new jlabel("days alive: " + idaysalive); lbldaysalive.setfont(new font("calibri", font.bold, 18)); lbldaysalive.setbounds(135, 257, 147, 21); frame.getcontentpane().add(lbldaysalive); } }
you declaring idaysalive inside action listener line
double idaysalive;
if declared inside action listener can't use outside.
you need define idaysalive somewhere can accessed inialize function. suggest making field of class.
Comments
Post a Comment