Edit: I have solved the underlying problem. I used
SwingUtilities.invokeLater()
to solve the issue. My other question provides more information for those who are interested.
I have a GUI that displays an image on a JPanel
in paintComponent()
with g.drawImage()
. I wrote a subclass of JPanel
called CanvasPanelView
to override paintComponent()
and do a few other things, like set the bounds of where the image is drawn. The problem is that I need to get the JPanel's width and height and when I call this.getWidth()
and this.getHeight()
in the class that extends JPanel, they both return 0
.
The process starts in an action listener inner class:
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();
}
}
}
}
Then, addDocument()
is called:
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()
is called:
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
is a wrapper class for CanvasPanel
and a few other things - it just groups together things that go with each open document.
Everything seems to be instantiated and used or added to the JTabbedPane
, so I don't know why this.getWidth()
and this.getHeight()
return 0
. Maybe something is happening between the end of setBounds()
and paintComponent()
.
Why do this.getWidth()
and this.getHeight()
return 0
?