我正在学习使用Java Swing绘制线条以绘制迷宫.我可以在指定的位置绘制一条线,它显示得很好.但是当我想画多行时,只有最后一行显示.我的代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
我可能需要刷新一些东西,以显示用for-loop绘制的所有线条,但不知道是什么.
Pin*_*juh 11
为什么你的例子不起作用很简单; Swing使用布局管理器将添加到a的每个组件Container放到屏幕上.这样,线条不重叠.
相反,使用Component绘制每一行的一个.绘制迷宫的解决方案是:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后用来Labyrinth.addLine为你的迷宫添加线条.也; Labyrinth通过调用setBounds或类似方式为您指定宽度和高度,因为Swing可能正在裁剪图形.