I'm learning drawing lines with Java Swing in order to draw a labyrinth. I can draw one line at a specified position and it shows just fine. But when I want to draw multiple lines, only the last one shows. My code:
public class LabyrinthGUI extends JFrame {
...
Line line;
for (int i = 0; i < 10; i++) {
line = new Line(i*25, 0, (i+1)*25, 50);
this.getContentPane().add(line);
}
}
public class Line extends JPanel{
private int x1, y1, x2, y2;
public Line(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public void paintComponent (Graphics g) {
g.drawLine(x1, y1, x2, y2);
}
I probably have to refresh something, to display all the lines drawn with for-loop, but don't know what.
Why your example doesn't work is a simple one; Swing uses a layout manager to place every component added to a Container
onto the screen. This way, the lines do not overlap.
Instead, use one Component
in which every line is drawn. A solution for drawing a maze would be:
public class Labyrinth extends JPanel {
private final ArrayList<Line> lines = new ArrayList<Line>();
public void addLine(int x1, int y1, int x2, int y2) {
this.lines.add(new Line(x1, y1, x2, y2));
}
public void paintComponent(Graphics g) {
for(final Line r : lines) {
r.paint(g);
}
}
}
public static class Line {
public final int x1;
public final int x2;
public final int y1;
public final int y2;
public Line(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
}
public void paint(Graphics g) {
g.drawLine(this.x1, this.y1, this.x2, this.y2);
}
}
And then use Labyrinth.addLine
to add lines to your labyrinth. Also; specify a width and height for your Labyrinth
, by calling setBounds
or similar, because Swing may be cropping the graphics.
Your problem pretty much boils down to this:
public class Line extends JPanel
Think of each JPanel as an opaque card with something drawn on it. You're creating a bunch of these, each with a single line drawn on it, and then stacking them up on top of each other. That's why you can only see the most recent line.
Instead, you should have only one component that draws all of your lines in its paintComponent
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With