我正在尝试使用线条在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();
}
}
}
问题是&#39; this.getHeight()&#39;和&#39; this.getWidth()&#39;两者都返回0,因此网格不会被绘制。绘制线条工作正常,它只是面板显然没有维度。我该如何解决这个问题。
答案 0 :(得分:4)
不是主要问题,但您需要覆盖类的getPreferredSize()
方法以返回大小。
每个组件负责确定自己的首选大小。 然后,当面板添加到父面板时,布局管理器可以使用此信息。
当然这假设父面板正在使用你应该做的布局管理器。
有关更多信息和工作示例,请阅读Custom Painting
上的Swing教程中的部分真正的问题是当你调用以下方法时:
initWorkSpace();
创建组件时,所有组件的大小均为零。因此,当从构造函数调用上述方法时,大小将始终为零。
如果您的绘图代码是动态的,这意味着它会随着框架的大小调整而更改,那么您需要在paintComponent()方法中调用该逻辑。
或者,如果每次重新绘制组件时逻辑太复杂而无法执行,则可以向面板添加ComponentListener
并处理componentResized
方法并调用该方法。
另外,在进行自定义绘画时,我不确定为什么要使用GroupLayout。