The goal is to draw a bunch of circles (each a separate JComponent instance) onto a JPanel, and to be able to scroll far enough in any direction to see all of them.
Here is the “main” code:
JFrame frame = new JFrame();
JPanel p = new JPanel(new BorderLayout());
p.add(new Circle(-100, 0, 200));
p.add(new Circle(-25, 0, 650));
JScrollPane scrollPane = new JScrollPane (p);
frame.add(scrollPane);
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Here is the Circle class:
public class Circle extends JComponent {
private int x;
private int y;
private int width;
public Circle(int x, int y, int width) {
this.x = x;
this.y = y;
this.width = width;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(this.x, this.y, this.width, this.width);
}
}
A couple of problems I can’t seem to solve:
- JPanel doesn’t show any circles unless its layout is set to BorderLayout; when it is set to BorderLayout, it only shows the last circle that has been added to it.
- I tried using a JScrollPane to make the JPanel scrollable. However, when I draw an oversized circle to check if it works, JScrollPane doesn’t show a scrollbar to see all of it. (See below)
Unscrollable, can’t see entire component.
Hopefully this is halfway understandable, I’m very very new to Swing. Any ideas would be super highly appreciated!
Dilara is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.