I am trying to make an application, but currently a bit stuck on how to neatly structure my code.
For simplicity, suppose i want a JFrame
that contains:
- A
JPanel
which contains aJComboBox
in which a user can select a shape (square, circle etc.). - A separate
JPanel
that visually displays the selected shape in theJComboBox
.
So I have the following code:
public class Frame extends JFrame {
Frame() {
ComboBoxPanel comboBoxPanel = new ComboBoxPanel();
ShapePanel shapePanel = new ShapePanel();
this.getContentPane().add(comboBoxPanel, BorderLayout.WEST);
this.getContentPane().add(shapePanel, BorderLayout.CENTER);
this.setResizable(true);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
new Frame();
}
}
ComboBoxPanel:
public class ComboBoxPanel extends JPanel {
private JComboBox<Shape> comboBox;
ComboBoxPanel() {
comboBox = new JComboBox<Shape>(Shape.SHAPES);
this.add(comboBox);
comboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
// Here I want to repaint the shapePanel
}
}
});
}
}
Finally, ShapePanel will look something like:
public class ShapePanel extends JPanel {
@Override
public void paintComponent(Graphics g) {
// Get selected Shape from JComboBox and draw it
}
}
In short, how can I let these two same-level-components interact with each other in a neat way? I have thought of some solutions but they look really dirty. Any thoughts are welcome.
Thanks.