Java – how do I change the value of jtextfield?

I'm trying to build a Java application using JFrame and swing. I have five jtextfield instances One of them is sum

I need to change jtextfield automatically when I enter some numbers in the text field

How is that possible?

I wrote 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 try to get the sum and use the button to display it in this text field and it works But I hope it will be done automatically But the above code does not display anything on textfield

I'm a stranger to this. I'd appreciate it if you could guide me

Solution

I think you're looking for

>Settext() method of jtextfield. > Writing a documentlistener knows when text changes and applies summation > writing a documentfilter to ensure that your program does not crash because the input is different from the number

Another method is to use jformattedtextfield and listener

some suggestions.

>Development intuition, usually the attributes of Java classes are changed by the (get | set) attribute Use an IDE like NetBeans, which can help you find things. > Automation is usually achieved by using listeners, just knowing when to use them (which is also part of intuition). > When you find yourself writing duplicate code, consider using functions Namely

Instead of six times:

display1b.getText().equals("") ? 0 : Float.parseFloat(display1b.getText());

Consider putting your fields in an ArrayList and writing a function that iterates over them, using the line above to set all the values

>Extra effort to hard code according to Java tutorials, or ask here It will be more effective for you Because you will learn how to learn by yourself and learn more about documents

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>