0

编辑: 我已经解决了根本问题。我曾经SwingUtilities.invokeLater()解决这个问题。我的另一个问题为感兴趣的人提供了更多信息。

JPanel我有一个 GUI,可以在.inpaintComponent()上显示图像g.drawImage()。我写了一个JPanel被调用的子类CanvasPanelView来覆盖paintComponent()并做一些其他的事情,比如设置图像绘制位置的边界。问题是我需要获取 JPanel 的宽度和高度,当我调用this.getWidth()this.getHeight()在扩展 JPanel 的类中时,它们都返回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,所以我不知道为什么this.getWidth()this.getHeight()返回0setBounds()也许在和的结尾之间发生了一些事情paintComponent()

为什么this.getWidth()this.getHeight()返回0

4

2 回答 2

1

与其做一个'setBounds',不如把你的documentView放在一个Panel(BorderLayout)中,在一个位置,比如BorderLayout.CENTER?

或者,您可以根据图像尺寸设置文档视图的最小和首选尺寸。

于 2013-05-11T14:31:16.730 回答
0

你写了一个类,CanvasPanelView. 这个类扩展了JPanel. 看来,在您的实施中,setBounds您没有提及该成员JPanelgetHeight()参考getWidth()。因此,底层对象的高度为 0,宽度为 0。

如果您希望使用JPanel高度和宽度的值,那么您只需要确保为它们分配值。

于 2013-05-11T14:30:43.087 回答