我试图在带有线条的 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,因此不会绘制网格。绘制线条效果很好,只是面板显然没有尺寸。我该如何解决这个问题。
不是主要问题,但您需要覆盖getPreferredSize()
类的方法以返回大小。
每个组件负责确定自己的首选大小。然后,当面板添加到父面板时,布局管理器可以使用此信息。
当然,这假设父面板正在使用您应该做的布局管理器。
有关更多信息和工作示例,请阅读有关自定义绘画的 Swing 教程中的部分
真正的问题是当您调用以下方法时:
initWorkSpace();
创建组件时,所有组件的大小都为零。因此,当从构造函数调用上述方法时,大小将始终为零。
如果您的绘画代码是动态的,这意味着它会随着框架的大小调整而变化,那么您需要在paintComponent() 方法中调用该逻辑。
或者,如果您的逻辑太复杂而无法在每次重新绘制组件时执行,您可以将 a 添加ComponentListener
到面板并处理该componentResized
方法并调用该方法。
另外,我不确定为什么在进行自定义绘画时要使用 GroupLayout。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句