We have a controller where we have a pre-declared JList and JLabel that we are adding to a JPanel. Outside of the initial layout/adding code I can update a JLabel (e.g. change its text) but I can’t change the selection of the JList (e.g. jlist.setSelection(index) ) where it will update the UI. Code Below:
public class Test {
private JPanel myPanel;
private JList myList;
private JLabel myLabel;
public Test() {
//Some init code here...
this.myPanel = new JPanel();
this.myPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
String[] values = {"Value1", "Value2", "Value3", "Value4"}; //etc. etc.
this.myList = new JList(values);
this.myPanel.add(this.myList, gbc); //Add to panel
this.myLabel = new JLabel("Label1");
this.myPanel.add(this.myLabel, gbc); //Add to panel
//Add some code here to add it to a frame or something to display
}
public void updateLabel(String workingNewLabel) {
//The following works...
this.myLabel.setText(workingNewLabel);
// as in the label component in the JPanel will
//now be updated to the new value of workingNewLabel
}
public void changeSelectionInListToSomeIndex(int nonWorkingNewIndex) {
//The following does NOT update the JList in the panel...
//the selection remains whatever it was last set to.
this.myList.setSelectedIndex(nonWorkingNewIndex);
}
}
I’ve been able to get around this by iterating through all the components in myPanel looking for the JList component then set it to to myList eg.
//Code that goes after the line this.myPanel.add(this.myList, gbc);
for(Component component : this.myPanel.getComponents() ) {
//Iterate through it all until...
if (component.getClass() == this.myList.getClass()) {
this.myList = (JList) component; //cast the component as JList
}
}
Why do I need to do this for a JList but not for the JLabel? This is a workaround but it seems extremely hack-ish.
Thanks in advance!
-Daniel
@JB’s right. Here’s a working sscce: