swing - nullpointerexception error in java gui -
i new cs student learning java. trying make gui user enter number , display result. getting errors not familiar with. have tried searching in google didnt help. comment appreciated. thanks.
main method person class
import javax.swing.jframe; public class person { public static void main(string[] args) { jframe frame= new guifirst();//line 6 frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setvisible(true); } }
guifirst class
import javax.swing.jframe; import java.awt.event.actionlistener; import java.awt.event.actionevent; import javax.swing.jlabel; import javax.swing.jpanel; import javax.swing.jbutton; import javax.swing.jtextfield; public class guifirst extends jframe{ private jlabel label; private jlabel label1; private jtextfield text; private jbutton button; private jpanel panel; public guifirst(){ label=new jlabel("enter number"); setsize(450,100); text=new jtextfield(15); button=new jbutton("calculate"); class addaction implements actionlistener{ public void actionperformed(actionevent event){ double number=double.parsedouble(text.gettext()); double result=number*number; label1=new jlabel("your result is"+result); } } actionlistener listener=new addaction(); button.addactionlistener(listener); panel=new jpanel(); panel.add(label); panel.add(label1);//line 32 panel.add(text); panel.add(button); add(panel); } }
errors:
exception in thread "main" java.lang.nullpointerexception @ java.awt.container.addimpl(container.java:1090) @ java.awt.container.add(container.java:410) @ person.guifirst.<init>(guifirst.java:32) @ person.person.main(person.java:6)
you haven't initialized label1
line fails
panel.add(label1);
you're trying initialize in method won't called until ui generated , button clicked
class addaction implements actionlistener{ public void actionperformed(actionevent event){ double number=double.parsedouble(text.gettext()); double result=number*number; label1=new jlabel("your result is"+result); } }
this won't work because code won't executed until action performed. component
(the label) needs non null
before can added jpanel
.
you need initialize default value start with.
Comments
Post a Comment