[英]getHeight() and getWidth() both return 0
我試圖在帶有線條的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()方法內調用該邏輯。
或者,如果您的邏輯過於復雜而無法在每次重新繪制組件時執行,則可以向面板添加ComponentListener
並處理componentResized
方法並調用該方法。
另外,我不確定在進行自定義繪畫時為什么使用GroupLayout。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.