A
A
Alexander2015-05-05 07:32:36
Java
Alexander, 2015-05-05 07:32:36

How to create a "change" event for a variable in Java?

There is a variable with type double. The value of this variable is calculated in an infinite loop and it is constantly changing. This value should be displayed on the form in JTextField. Now I have created a simple class that inherits from JTextField:

public class ChartTabTextField extends JTextField {
    private double factor = 1.0;
    private String format = "%d";

    public ChartTabTextField(double d, String format, double factor) {
        this.factor = factor;
        this.format = format;
        setText(d);
    }

    public void setText(double d) {
        if (format.equals("%d")) {
            setText(String.format(format, (int) (d * factor)));
        } else {
            setText(String.format(format, d * factor));
        }
    } 
}

it gets into the form like this:
ChartTabTextField jtf = new ChartTabTextField(ve.pot.params.amp, "%.1f", 0.001);
jPanel1.add(jtf);

Question: how to bind the value of the variable ve.pot.params.amp to jTextField?
The option with setText from the loop body is not suitable, because there will be many such variables (as well as components on the form) and they are all calculated in different places, or may not be calculated. In general, I want some universality or simplification or something: I added the output of the necessary variable to the form and it automatically became "tracked". How and with the help of what classes to write such a "tracker" so that it automatically does setText?
ps well, as in QML: if you create a text field there and set a global variable to the text, then the text will automatically change along with the value of this variable. You don't even have to do anything :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
one pavel, 2015-05-05
@onepavel

See, there are 2 main ways an object interacts with another object.
1 object gets another object,
2 object takes what it needs.
If you don't want to do setText, then JTextField itself should take the value.
You should move away from the primitive to value boxing, or better create a class
that will control the change, and JTextField can act
as a listener through some interface

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question