swing - Sum of two text fields in Java -
i have been tearing hair out trying work. appreciated! goal: on jframe, have 2 text fields input numbers. press button sums numbers. display sum on label, located on jframe.
this have far. appreciate help! thank you!
import javax.swing.*; import java.awt.*; import java.awt.event.*; class homework181 extends jframe { private container contentpane; private jpanel panel1, panel2; private jbutton button1; private jtextfield text1; private jradiobutton radio1; private jradiobutton radio2; private buttongroup group; private actionlistener listener; private int count; public homework181(){ settitle("homework181"); setdefaultcloseoperation(jframe.exit_on_close); panel1=new jpanel(); panel1.setbackground(color.black); panel1.setpreferredsize(new dimension(300,100)); listener = new listener(); button1= new jbutton("sum"); button1.addactionlistener(listener); panel1.add(button1); panel2= new jpanel(); panel2.setbackground(color.yellow); panel2.setpreferredsize(new dimension(200,100)); text1=new jtextfield(10); count=0; text1.settext(""+ count); text1.addactionlistener(listener); panel2.add(text1); contentpane= getcontentpane(); contentpane.setlayout(new flowlayout()); contentpane.add(panel1); contentpane.add(panel2); pack(); setvisible(true); } public static void main(string[] args) { homework181 window= new homework181(); } private class listener implements actionlistener { public void actionpreformed(actionevent e) { if (e.getsource()==text1) count= integer.parseint(text1.gettext()); else if (e.getsource()==button1); text1.settext(""+ ++count); } @override public void actionperformed(actionevent arg0) { // todo auto-generated method stub } } }
try instead of create listener class :
actionlistener listener = new actionlistener() { public void actionperformed(actionevent e) { if (e.getsource() == text1) { count = integer.parseint(text1.gettext()); } else if (e.getsource() == button1) { text1.settext("" + ++count); } } };
this function increament value in text1
if want sum of 2 text , create 1 , :
jtextfield text2 = new jtextfield(10); text2.settext("" + count); text2.addactionlistener(listener); panel2.add(text2);
then :
create jlabel :
jlabel sum = new jlabel(); sum.settext("" + count); panel2.add(sum);
then: actionlistener listener = new actionlistener() {
public void actionperformed(actionevent e) { count = integer.parseint(text1.gettext()) + integer.parseint(text2.gettext()); if (e.getsource() == button1) { sum.settext("" + count); } } };
and instead of of , make action jbutton( because action need) , :
button1.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent e) { count = integer.parseint(text1.gettext()) + integer.parseint(text2.gettext()); text1.settext("" + count); } });
Comments
Post a Comment