Java swing gets all editable jformattedtextfields and computes?

I am trying to make a calculator that basically looks like this one: the user enters about 18-19 values, then he presses the button and the result is equal to his sum of input divided by the number of fields. However, this is much more complicated. The user can specify some parameters that will add more input fields (basically make the option when he creates an editable jformattedtextfield, when it is not edited by default), this can be a huge timewaster, since I have to write a huge IF statement, which I "Hate Basically, the user can activate some jSpinners that greatly expand the capabilities of jFormattedTExtFields than the default settings. I ask how you can check which jformattedtextfields are edited and which are not, and then run about editions with editable?

+1
source share
4 answers

add DocumentListener to all JFormattedTextFields and accept the value from the Number instance, for eample for Float

 if (someTextField.isEditable()){ float newValue = (((Number) resistorValue.getValue()).floatValue()); } 
+2
source

First of all, define the container that hosts the jformattedtextfield, and then simply use the JContainer API to move all the child components and filter all jformattedtextfield components using instanceof.

For instance:

 public static int calcIfEnabled(Container container) { int finalResult = 0; for (Component c : container.getComponents()) { if (c instanceof JFormattedTextField && c.isEnabled() && ((JFormattedTextField) c).isEditable()) { finalResult += Integer.parseInt(((JFormattedTextField) c).getText()); } } return finalResult; } 

UPD: Of course, you can enable the entire child component using recursion and pass in the main container (JFrame), but that would not be so good in terms of performance.

 public static int calcIfEnabled(Container container) { int finalResult = 0; for (Component c : container.getComponents()) { if (c instanceof JFormattedTextField && c.isEnabled() && ((JFormattedTextField) c).isEditable()) { finalResult += Integer.parseInt(((JFormattedTextField) c).getText()); } else if (c instanceof Container) { finalResult += calcIfEnabled((Container) c); } } return finalResult; } 
+1
source

The easiest way would be to add a JFormattedTextField to the array when you create a new one. And then, when required, iterate over the array and check if it can be edited.

+1
source

It looks like your model can be complex enough to guarantee the use of the Model View Controller template. Your model will determine which fields make sense for the representation to display for a given controller state. It also ensures that the displayed response is equally consistent. This example may offer additional recommendations.

+1
source

Source: https://habr.com/ru/post/1388969/


All Articles