UI의 두 요소를 연결하는 가장 간단한 해결책은이를 클래스로 결합하는 것입니다. 그런 다음 다른 요소에서 해당 요소를 참조하는 것이 명확 해집니다. 같은
뭔가 :
class LabelPanel {
JLabel label;
JPanel pane;
...
}
기본 작업 예 :
이
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);
}
}
이것은 실제 상황에 적응하기 너무 어렵지 않을 것이다.
아니요 나는이 JLabel이 많기 때문에 각 레이블에 직접 메서드를 호출하면 지옥이 될 것이라고 말합니다 –
올바르게 이해한다면 레이블을 패널에 매핑해야합니다. 왜 'HashMap'을 사용하지 않고 왜 클릭 한 라벨과 연결된 패널? – user1803551
그런 다음 HashMap을 사용하여 긴 목록을 작성하고 각 JPanel의 이름과 위치를 추적하여 해당 목록에서 호출 할 수 있도록해야합니다. 따라서 JLabel에서 오는 문자열을 JPanel 변수 이름으로 변환 할 수 있다면 더 좋은 아이디어가 될 수 있습니다. –