I am trying to built a Java application using JFrame
with Swing, and I have 5 JTextField
instances in there. One of these is for Sum.
I need JTextField
to change automatically as soon as I type some number in text fields.
How is that possible?
What I wrote is here.
private void displaytotalActionPerformed(java.awt.event.ActionEvent evt) {
// display total:
Float num1,num2,num3,num4,num5,num6,result;
num1 = display1b.getText().equals("") ? 0 : Float.parseFloat(display1b.getText());
num2 = display2b.getText().equals("") ? 0 : Float.parseFloat(display2b.getText());
num3 = display3b.getText().equals("") ? 0 : Float.parseFloat(display3b.getText());
num4 = display4b.getText().equals("") ? 0 : Float.parseFloat(display4b.getText());
num5 = display5b.getText().equals("") ? 0 : Float.parseFloat(display5b.getText());
num6 = display6b.getText().equals("") ? 0 : Float.parseFloat(display6b.getText());
result = num1+num2+num3+num4+num5+num6;
System.out.println(result);
}
I tried to get the sum and display it in this textfield using button and it worked. But i want it to be done automatically. But the code above doesnt display anything on textfield.
I am quite new to this and I appreciate if you kindly guide.
I think you're looking for
setText()
method of a JTextField
.An alternative to this is to use a JFormattedTextField and using listeners.
A couple of recommendations.
(get|set)Property
. Use an IDE like Netbeans and it will help you finding stuff.Instead of having 6 times:
display1b.getText().equals("") ? 0 : Float.parseFloat(display1b.getText());
Consider having your fields in an ArrayList
and write a function that iterates them and have a single line of the above to set all the values.