Multiple Interdependent JComponents without Recursive Loop

84 views Asked by At

For the smallest example, I have three Swing JComponent elements that need to interact with each other: a JSlider, and two JTextFields. The JSlider goes from 0 to 50, one of the JTextFields shows the value of the JSlider and the second JTextField shows the percentage of the total value (i.e. 2 in the JSlider would update 4% in the second JTextField).

A change in any one of the three elements should update all the others. So a ChangeEvent in the JSlider should trigger setText() events in the JTextFields. However, setText() triggers ActionEvents in the TextFields which should, in this case, trigger a change in value for the JSlider.

I've been tackling this problem with a "refreshing" boolean flag, where the boolean would be checked before processing the ActionEvent / ChangeEvent. but I'd like to know if there's any more programmatic or cleaner way of preventing the ActionEvent / ChangeEvent loop.

I'd appreciate any insights!


Edit

I'm attempting to make this work with histogram information, where the percentage values will not exactly match the slider values (i.e. there will be rounding errors). The suggested SpinSliders relies on the setText() method being able to "settle" on a final value. In other words, if the value input to setText() is the same as the text it already holds, it does not fire an ActionEvent, effectively ending the loop. If the rounding is off, the setValue() of the JSlider and the setText() of the JTextField will never reach an "equilibrium" state due to rounding. I hope that describes the problem succinctly.

1

There are 1 answers

0
trashgod On BEST ANSWER

SpinSlider may be a useful starting point. As you must be able to "settle" on a final value, use getValueIsAdjusting() to update once the final value is available.