java - Can't access these variables outside the ActionListener -
i have been stuck on weekend, have looked everywhere , not single solution. appreciated.
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 = 0; calendar cabirthdate = new gregoriancalendar(iyearbirth, imonthbirth - 1, idaybirth); calendar cacurrentdate = new gregoriancalendar(iyearcurrent, imonthcurrent - 1, idaycurrent); jbutton btncalculate = new jbutton("calculate"); btncalculate.addactionlistener(new actionlistener() { public void actionperformed(actionevent e) { idaysalive = (cacurrentdate.gettimeinmillis() - cabirthdate.gettimeinmillis()); idaysalive = (idaysalive / (24 * 60 * 60 * 1000) + 1); // error here: "cannot refer non-final variable cabirthdate inside inner class defined in different method //get same error for, cabirthdate , idaysalive } }); btncalculate.setfont(new font("calibri", font.bold, 12)); btncalculate.setbounds(188, 187, 89, 23); frame.getcontentpane().add(btncalculate); jtextfield_result = new jtextfield("total days alive: " + idaysalive); jtextfield_result.setbounds(150, 233, 170, 20); frame.getcontentpane().add(jtextfield_result); jtextfield_result.setcolumns(10);
if move calender , integer variable inside actionlistener can't access idaysalive variable in final textfield.
a solution create class implements action listener. can give tha class access variable needed:
class actionhandler implements actionlistener { public actionhandler (mainclass mainclass) { //now getters of main class can called } public void actionperformed(actionevent e) { } }
Comments
Post a Comment