-1

I need to display BufferedImage on a JPanel with Netbeans. I add the panel using Netbeans' drag and drop. Then I added code to display the image on the panel. Here is my code:

BufferedImage img = null;
try {
    img = ImageHelper.loadImage(path);
} catch (IOException ex) {
    Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
}
ImageIcon icon = new ImageIcon(img);
JLabel picLabel = new JLabel(icon);

//imagePlace is JPanel
imagePlace.add(picLabel);
imagePlace.repaint();

But it didn't paint the image on the panel. I have followed some tutorials but not working at all. Can you give an example the correct way to display BufferedImage on JPanel?

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tubes;

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import static jdk.nashorn.tools.ShellFunctions.input;

/**
 *
 * @author ivan
 */
public class MainGUI extends javax.swing.JFrame {

/**
 * Creates new form MainGUI
 */
public MainGUI() {
    initComponents();        
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jTabbedPane1 = new javax.swing.JTabbedPane();
    jPanel1 = new javax.swing.JPanel();
    openImageBtn = new javax.swing.JButton();
    imagePlace = new javax.swing.JPanel();
    canvas1 = new java.awt.Canvas();
    jPanel2 = new javax.swing.JPanel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanel1.setPreferredSize(new java.awt.Dimension(512, 512));

    openImageBtn.setText("Open Image");
    openImageBtn.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            openImageBtnActionPerformed(evt);
        }
    });

    imagePlace.setBackground(new java.awt.Color(254, 254, 254));

    javax.swing.GroupLayout imagePlaceLayout = new javax.swing.GroupLayout(imagePlace);
    imagePlace.setLayout(imagePlaceLayout);
    imagePlaceLayout.setHorizontalGroup(
        imagePlaceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 178, Short.MAX_VALUE)
    );
    imagePlaceLayout.setVerticalGroup(
        imagePlaceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 194, Short.MAX_VALUE)
    );

    canvas1.setBackground(new java.awt.Color(255, 0, 0));

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(openImageBtn)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(imagePlace, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 253, Short.MAX_VALUE)
                    .addComponent(canvas1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(80, 80, 80))))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(openImageBtn)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(imagePlace, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(96, 96, 96)
                    .addComponent(canvas1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(144, Short.MAX_VALUE))
    );

    jTabbedPane1.addTab("tab1", jPanel1);

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 523, Short.MAX_VALUE)
    );
    jPanel2Layout.setVerticalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 387, Short.MAX_VALUE)
    );

    jTabbedPane1.addTab("tab2", jPanel2);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(20, 20, 20)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 535, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(108, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(25, Short.MAX_VALUE)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 430, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
    );

    pack();
}// </editor-fold>                        

private void openImageBtnActionPerformed(java.awt.event.ActionEvent evt) {                                             
    // TODO add your handling code here:
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
    int result = fileChooser.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();
        String path = selectedFile.getAbsolutePath();
        System.out.println(path);
        BufferedImage img = null;
        try {
            img = ImageHelper.loadImage(path);
        } catch (IOException ex) {
            Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        ImageIcon icon = new ImageIcon(img);
        JLabel label = new JLabel("", icon, JLabel.CENTER);
        JLabel picLabel = new JLabel(icon);
        imagePlace.add(picLabel);
        imagePlace.repaint();
    }
}                                            

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new MainGUI().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private java.awt.Canvas canvas1;
private javax.swing.JPanel imagePlace;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JButton openImageBtn;
// End of variables declaration                   
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
CherryBelle
  • 1,302
  • 7
  • 26
  • 46
  • 1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) BTW - Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An [tag:embedded-resource] must be accessed by URL rather than file. See the [info. page for embedded resource](http://stackoverflow.com/tags/embedded-resource/info) for how to form the URL. – Andrew Thompson Oct 05 '16 at 18:04
  • Logically, all that code after the end of the `catch` should be within the `try` code block since it will fail if the `try` fails. – Andrew Thompson Oct 05 '16 at 18:06
  • `img = ImageHelper.loadImage(path);` Try copy/pasting the code into a new project in the IDE and compiling it. Then you might notice that the `ImageHelper` class that loads the image is missing. It is probably the only relevant part of all the code. So again.. post an MCVE! One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). BTW - it should not take > 200 lines of code to load and display an image. 40 LOC tops. Put more effort into narrowing the problem down to just loading an image! – Andrew Thompson Oct 09 '16 at 01:30

1 Answers1

1

When you add a component to a visible GUI the basic code is:

    imagePlace.add(imgpnl);
    imagePlace.revalidate(); //added
    imagePlace.repaint();

You need the revalidate to invoke the layout manager, otherwise the component may have a size of (0, 0) so there is nothing to paint.

javax.swing.GroupLayout imagePlaceLayout = new javax.swing.GroupLayout(imagePlace);
imagePlace.setLayout(imagePlaceLayout);

However, the bigger problem is that you are using a GroupLayout and you didn't specify any constraints for the GroupLayout. Read the Swing tutorial on How to Use GroupLayout for information on the constraints and working examples.

Personally, I suggest you get rid of the code generator (and the GroupLayout) and create the GUI layout yourself if you want to dynamically add components to the frame. Start by just using a FlowLayout on your "imagePlace" panel. The code will be much simpler since you don't need any constraints.

camickr
  • 321,443
  • 19
  • 166
  • 288