How to change the value of the JTextField?

user1971804 picture user1971804 · Jan 12, 2013 · Viewed 9.1k times · Source

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.

Answer

Roger picture Roger · Jan 12, 2013

I think you're looking for

An alternative to this is to use a JFormattedTextField and using listeners.

A couple of recommendations.

  • Develop intuition, usually properties to java classes are changed by (get|set)Property. Use an IDE like Netbeans and it will help you finding stuff.
  • Automatization is usually achieved by using a Listener, just learn when to use which (this is also part of intuition).
  • When you find yourself writing repeated code, consider using a function. i.e.

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.

  • Follow the JavaTutorials before additional efforts of hard-coding, or asking here. Will be more productive to you. Because you will learn how to learn for yourself and dig into documentation.