Reputation:
I'm working on a program that will read a folder of images into a JList, and the picture that is selected in the JList will be drawn into a JPanel. I have two classes: ImageViewerPanel
, which creates the panel to display the selected picture. I then have ImageViewerUI
which will draw the JList, and the ImageViewerPanel
will be added into the ImageViewerUI
class. Here is the relevant code from the ImageViewerPanel
class.
public ImageViewerPanel() {
initComponents();
}
public void setImage(BufferedImage image) {
this.image = image;
repaint();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (scaled == false) {
g.drawImage(image, 0, 0, null);
}else if(scaled == true) {
g.drawImage(image, 0, 0, 80, 80, null);
}
Here is the code from the ImageViewerUI
class that is to refresh the panel with the image:
ImageViewerPanel imagePanel = new ImageViewerPanel();
BufferedImage displayedImage;
BufferedImage originalImage;
public ImageViewerUI() {
initComponents();
loadListWithImageFilenames();
updateImagePanel();
updateThumbnailImagePanel();
}
public final void updateImagePanel() {
try {
String currFile = (String) ("Images/" + imageList.getSelectedValue());
displayedImage = ImageIO.read(new File(currFile));
imagePanel.setImage(displayedImage);
} catch (IOException ex) {
Logger.getLogger(ImageViewerUI.class.getName()).log(Level.SEVERE, null, ex);
}
public final void updateThumbnailImagePanel() {
try {
String currFile = (String) ("Images/" + imageList.getSelectedValue());
originalImage = ImageIO.read(new File(currFile));
imagePanel.setScaled(true);
imagePanel.setImage(originalImage);
imageViewerPanel1.add(imagePanel);
imagePanel.repaint();
} catch (IOException ex) {
Logger.getLogger(ImageViewerUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
The issue I am having is that the image is not being displayed in the panel. Anyone know why?
Upvotes: 0
Views: 121
Reputation: 324207
imageViewerPanel1.add(imagePanel);
imagePanel.repaint();
When you add components to a visible GUI the code should be:
imageViewerPanel1.add(imagePanel);
//imagePanel.repaint();
imageViewerPanel1.revalidate();
imageViewerPanel1.repaint();
All components are created with a size of (0, 0) so there is nothing to paint. The revalidate() invokes the layout manager which in turn gives a size to the compoenent.
As mentioned above you will also need to override the getPreferredSize() method of you imagePanel so the layout manager can determine the proper size of the panel.
Upvotes: 1