I would say that the simplest solution to associate 2 elements of the UI is to combine them into a class. Then referencing the corresponding element from the other becomes obvious.
Something like:
class LabelPanel {
JLabel label;
JPanel pane;
...
}
Basic working example:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestLabelPanelComposition {
public static class LabelPanel {
private final JLabel label;
private final JPanel panel;
private Color colorToSet;
public LabelPanel(String labelText, final Color colorToSet) {
super();
this.colorToSet = colorToSet;
this.label = new JLabel(labelText);
this.panel = new JPanel();
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Color old= panel.getBackground();
panel.setBackground(LabelPanel.this.colorToSet);
LabelPanel.this.colorToSet = old;
}
});
}
public JLabel getLabel() {
return label;
}
public JPanel getPanel() {
return panel;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TestLabelPanelComposition().initUI();
}
});
}
protected void initUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Random r= new Random();
List<LabelPanel> labelPanels =new ArrayList<TestLabelPanelComposition.LabelPanel>();
for(int i=0;i<10;i++) {
LabelPanel labelPanel = new LabelPanel("My Label to click "+(i+1), new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
labelPanel.getPanel().add(new JLabel("Some dummy text inside panel "+(i+1)));
labelPanels.add(labelPanel);
}
frame.setLayout(new GridLayout(0, 5));
for (LabelPanel labelPanel : labelPanels) {
frame.add(labelPanel.getLabel());
}
for (LabelPanel labelPanel : labelPanels) {
frame.add(labelPanel.getPanel());
}
frame.pack();
frame.setVisible(true);
}
}
This should not be too hard to adapt to your actual situation .