I have a series of JLabels within an interface which are used to display the properties of an object. Is it possible to update the JComponents automatically if said object is replaced by another of the same class? Would such a method be considered bad practice? For example consider the following:
String stringToBeDisplayed = new String("String 1");
JLabel label = new JLabel(stringToBeDisplayed);
stringToBeDisplayed = new String("String 2");
//*Refresh label to show string change*
I know that the text of the JLabel could be set using JLabel.setText() or the label could be replaced, but I am lazy and these methods are a little inconvenient with many JComponents!
What you are trying to do will not even work, because re-initializing stringToBeDisplayed
will not affect anything you have passed it to--in this case, the JLabel()
constructor.
The way to do what you want is to call JLabel.setText()
. If you have a lot of components, you must make a lot of calls. You might be able to wrap some of them so you can call one of your methods to update many of them with a batch, but it's the way you'll have to do it. You might also be able to reduce your typing by putting your JLabel
s in Collection
s or arrays and using loops.
Although, in theory, you could subclass or composite JLabel
and add a method that accepts some String
-wrapping object that you would have to write the class for, and then you could have that class accept change listeners (an Observer pattern) and upon a change update the JLabel
.