Search code examples
javaimageswingjlabeljtextarea

How to upload image to JTextArea using JFileChooser and JLabel


I have a set of code which I have compiled without any errors. The code is supposed to select an image file from the local directory and upload to a JTextArea using JFileChooser and JLabel. But upon runtime, the image selected isn't displaying.

Below is the code snippet.

JLabel jLab=new JLabel();
private void openActionPerformed(java.awt.event.ActionEvent evt){
    JFileChooser jfc=new JFileChooser();
    if(jfc.showOpenDialog(jMenu1)==JFileChooser.APPROVE_OPTION){
        java.io.File f=jfc.getSelectedFile();
        jLab.setIcon(new ImageIcon(f.toString()));
        jtextareaDisplay.add(jLab, 0);
    }
}

Solution

  • jtextareaDisplay.add(jLab, 0);
    

    A JTextArea is for displaying text only, not images.

    The add(…) method will do nothing because the JTextArea does not use a layout manager, so the size of any component will be (0, 0) so there is nothing to paint.

    If you are trying to create a background for the text area, then you need to do custom painting by overriding the paintComponent() of the text area.

    If you really want an image and text displayed together then you need to use a JTextPane. The JTextPane supports an insertIcon(…) method.