Fashtaki Fashtaki - 1 month ago 12
Java Question

how to save a value from JTextField in a variable as non-editable value?

i have a JTextField for Double values as input which saved in a double variables :



JTextField textfield1 = new JTextField("0.0");


public void actionPerformed(ActionEvent arg0) {

d1 = Double.parseDouble(textfield1.getText());
d2 = Double.parseDouble(textfield1.getText());

}
d3 = d1 +d2 ;


if i enter as Example in the textfield1 = (10.2 ) it will be saved in both (d1 )and (d2) so then(d3) = (22.4)
BUT i want that first value i enter like (2.5) to be saved in (d1) and never changed then next value i enter like (3.5) to be saved in (d2) and never changed so then (d3) = (6.5)

HOW can i do that any help please ?.

Answer

This isn't really a Swing question but a basic logic question, and one solution is simple: use a boolean field, say d1Assigned, set it to false.

In the actionPerformed method, check the boolean via an if block. if false, then set it to true and assign d1. If true then don't assign d1.

private boolean d1IsAssigned = false;

// .....

@Override
public void actionPerformed(ActionEvent e) {
    if (!d1IsAssigned) {
        d1 = ....;
        d1IsAssigned = true;
    }

    // assign other fields here
}

Or, another way is to "lock" textfield1 after you have obtained your data from it by setting it to be no longer enabled. Something like:

@Override
public void actionPerformed(ActionEvent e) {
    if (textField1.isEnabled()) {
        d1 = Double.parseDouble(textfield1.getText());
        textField1.setEnabled(false);
    }
    d2 = Double.parseDouble(textfield1.getText());

    // assign other fields here
    // do calculation
}

I like this even better, since now the user cannot interact with the text field and knows that its value is "locked".

Comments