![](/img/trans.png)
[英]Why does getHeight() and getWidth() return 0 in the constructor? and how do I avoid that?
[英]Why do getWidth() and getHeight() return 0 before paintComponent() is called?
编辑: 我已经解决了潜在的问题。 我使用
SwingUtilities.invokeLater()
解决了这个问题。 我的其他问题为有兴趣的人提供了更多信息。
我有一个GUI,可以使用g.drawImage()
在paintComponent()
的JPanel
上显示图像。 我写了一个名为CanvasPanelView
的JPanel
子类来重写paintComponent()
并做其他一些事情,例如设置绘制图像的边界。 问题是我需要获取JPanel的宽度和高度,并且在扩展JPanel的类中调用this.getWidth()
和this.getHeight()
时,它们都返回0
。
该过程从动作侦听器内部类开始:
class MenuBarFileOpenListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
File fileChooserReturnValue = view.showAndGetValueOfFileChooser();
if (fileChooserReturnValue != null) {
try {
DocumentModel newDocument = new DocumentModel(ImageIO.read(fileChooserReturnValue), fileChooserReturnValue.getAbsolutePath(), fileChooserReturnValue.getName());
model.addDocument(newDocument);
view.addDocument(newDocument);
} catch(IOException ex) {
ex.printStackTrace();
}
}
}
}
然后, addDocument()
:
public void addDocument(DocumentModel document) {
menuBar_file_close.setEnabled(true);
DocumentView newDocumentView = new DocumentView(document.getTitle(), documentsTabbedPaneCloseButtonListener);
documentViews.add(newDocumentView); // add newDocumentView to ArrayList<DocumentView>
newDocumentView.setDocument(document);
documentsTabbedPane.add(newDocumentView.getCanvasPanelView());
int newDocumentIndex = documentsTabbedPane.indexOfComponent(newDocumentView.getCanvasPanelView());
documentsTabbedPane.setTabComponentAt(newDocumentIndex, newDocumentView.getTabPanel());
documentsTabbedPane.setSelectedIndex(newDocumentIndex);
newDocumentView.setBounds(document.getImageWidth(), document.getImageHeight());
}
public DocumentView(String title, ActionListener listener) {
canvas = new CanvasPanelView();
// more code...
}
setBounds()
称为:
public void setBounds(int imageWidth, int imageHeight) {
sourceX1 = 0;
sourceY1 = 0;
sourceX2 = imageWidth;
sourceY2 = imageHeight;
// some math...
destinationX1 = 0 + xMargin;
destinationY1 = 0 + yMargin;
destinationX2 = drawWidth - xMargin;
destinationY2 = drawHeight - yMargin;
}
DocumentView
是CanvasPanel
和其他一些东西的包装器类-它将每个打开的文档附带的东西分组在一起。
一切似乎JTabbedPane
实例化并使用或添加到JTabbedPane
,所以我不知道为什么this.getWidth()
和this.getHeight()
返回0
。 可能在setBounds()
和paintComponent()
的末尾之间发生了某些事情。
为什么this.getWidth()
和this.getHeight()
返回0
?
而不是执行“ setBounds”,为什么不将documentView放在Panel(BorderLayout)中,放在BorderLayout.CENTER之类的位置?
或者,您可以根据图像尺寸设置最小和首选的文档视图尺寸。
您已经编写了一个类CanvasPanelView
。 此类扩展了JPanel
。 看起来,在实现setBounds
您没有引用getHeight()
和getWidth()
引用的JPanel
成员。 因此,基础对象的高度为0,宽度为0。
如果希望将JPanel
值用于高度和宽度,则只需要确保为它们分配值即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.