【发布时间】:2017-02-25 17:08:52
【问题描述】:
我正在尝试用线条在 JPanel 中创建一个网格,为此,我绘制均匀间隔的水平和垂直线,直到到达 JPanel 的末端。我使用了一个名为 Drawing 的类,它扩展了 JPanel 并且是我添加到窗口中的对象。下面是我的代码。
public final class Drawing extends JPanel {
public Drawing() {
super();
setBackground(new Color(255, 255, 255));
setBorder(BorderFactory.createLineBorder(new Color(0, 0, 0)));
GroupLayout workspacePanelLayout = new GroupLayout(this);
setLayout(workspacePanelLayout);
workspacePanelLayout.setHorizontalGroup(workspacePanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 343, Short.MAX_VALUE));
workspacePanelLayout.setVerticalGroup(workspacePanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 400, Short.MAX_VALUE));
initWorkSpace();
}
private static class Line {
final int x1;
final int y1;
final int x2;
final int y2;
final Color color;
public Line(int x1, int y1, int x2, int y2, Color color) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.color = color;
}
}
private final LinkedList<Line> lines = new LinkedList<>();
public void addLine(int x1, int x2, int x3, int x4) {
addLine(x1, x2, x3, x4, Color.black);
}
public void addLine(int x1, int x2, int x3, int x4, Color color) {
lines.add(new Line(x1, x2, x3, x4, color));
repaint();
}
public void clearLines() {
lines.clear();
repaint();
}
@Override
private void paintComponent(Graphics g) {
super.paintComponent(g);
for (Line line : lines) {
g.setColor(line.color);
g.drawLine(line.x1, line.y1, line.x2, line.y2);
}
}
public void initWorkSpace() {
int x = 0;
int y = 0;
while (x < this.getWidth()) {
addLine(x, 0, x, this.getHeight(), new Color(153, 153, 153));
x += getSpacing();
}
while (y < this.getHeight()) {
addLine(0, y, this.getWidth(), y, new Color(153, 153, 153));
y += getSpacing();
}
}
}
问题是 'this.getHeight()' 和 'this.getWidth()' 都返回 0,所以网格不会被绘制。画线效果很好,只是面板显然没有尺寸。我该如何解决这个问题。
【问题讨论】:
-
当您提出问题时,请发布正确的minimal reproducible example。我们不知道该面板在您的实际应用程序中是如何使用的上下文,只能猜测。
-
我在 JSplitPane 的 Window 类中实例化了 Panel
-
声明不是minimal reproducible example。无论如何,你有一个建议,所以试试这个建议。如果您需要更多帮助,那么这个问题和所有未来的问题都应该附有适当的示例。
标签: java swing jframe jpanel paintcomponent