问题描述
我正在学习使用Java Swing绘制线条以绘制迷宫。我可以在指定位置绘制一条线,它显示得很好。但是当我想画多行时,只有最后一行显示。我的代码:
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);
}
我可能需要刷新一些东西,才能显示所有行用for循环绘制,但不知道是什么。
I probably have to refresh something, to display all the lines drawn with for-loop, but don't know what.
推荐答案
为什么你的例子不起作用很简单; Swing使用布局管理器将添加到 Container
的每个组件放到屏幕上。这样,线条不重叠。
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);
}
}
然后使用 Labyrinth。 addLine
将行添加到迷宫中。也;通过调用 setBounds
或类似来指定 Labyrinth
的宽度和高度,因为Swing可能会裁剪图形。
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.
这篇关于使用Java Swing绘制多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!