1

I'm trying to make a calculator which is basicly like this: user enters about 18-19 values, then he presses a button and the result is equal to his input sum divided by the number of fields. However, it's far more complex than that. The user can specify some options which add more input fields (Basicly make an option where he makes a jformattedtextfield editable, when by default it's non-editable), this can be a huge timewaster since I have to write a huge IF statement, which I'd hate doing. Basicly the user can activate some jSpinners which make more jFormattedTExtFields editable than the default options, significantly. What I'm asking is, how can you check which jformattedtextfields are editable, which aren't, and then perform operations with the ones which are editable?

Bugster
  • 1,552
  • 8
  • 34
  • 56

4 Answers4

2

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

if (someTextField.isEditable()){ 
    float newValue = (((Number) resistorValue.getValue()).floatValue());
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
1

First of all, determine container where jformattedtextfield is placed, then just use JContainer API to traverse all child components and filter all jformattedtextfield components using instanceof.

For example:

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 include all child component using recursion and pass main Container (JFrame), but it will be not so good from performance point.

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;
}
4ndrew
  • 15,354
  • 2
  • 27
  • 29
1

Simplest would be to add the JFormattedTextField to an array, whenever you create a new one. And then when required, iterator over the array and check whether it is editable.

Pragalathan M
  • 1,673
  • 1
  • 14
  • 19
1

It sounds like your model may be sufficiently complex to warrant using the Model View Controller pattern. Your model would specify which fields make sense for the view to display for a given controller state. It would also ensure that the displayed answer was similarly consistent. This example may offer additional guidance.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045