Hello everyone.

1)I am trying several days now to display an image from file Chooser in Netbeans. i have read and tried many different approaches from the web, but something goes wrong.Although the program runs ok,I see no results.Until now, I have used the "Design" tab of Netbeans to create one main Jframe and three Panels.
Panel1 for image preview(of course I will implement it much later)
Panel2 for buttons like "Add pic","remove" etc.The Add button opens my file Chooser.Now I am trying to load an image from the file Chooser inside Panel3 and of course fit it correctly according to Panel3's size.

The code for Add Button action is something like this:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
        File file;
        BufferedImage image=null;
        JFileChooser fileChooser = new JFileChooser();
        int returnValue = fileChooser.showOpenDialog(null);
       // myfileFilter filter = new myfileFilter();
       // fileChooser.addChoosableFileFilter(filter);

        if (returnValue == JFileChooser.APPROVE_OPTION){

                System.out.println("Ok");

             try{
                file=fileChooser.getSelectedFile();
                System.out.println("Selected file is"+ file);
                image=ImageIO.read(file);

               System.out.println("Ok");

               ImageIcon icon = new ImageIcon(image);
               JLabel picLabel = new JLabel(icon);

             //  picLabel.setIcon(icon);
               //picLabel.revalidate();
             //  picLabel.repaint();

               // JLabel picLabel = new JLabel(new ImageIcon(image));

               System.out.println("Ok");

               //picLabel.setIcon(icon);
               jPanel3.add(picLabel);
               jPanel3.invalidate();          
               jPanel3.repaint();
             //  int w = image.getWidth(null);
             //  int h = image.getHeight(null);
             //  BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);


          //    Graphics g = bi.getGraphics();
            //  g.drawImage(image,0,0,null);
             //   System.out.println("Ok");


        }catch(IOException e){

        }}
        }

As you can see I included all comment lines just to see what else I have tried.When I run the file,file Chooser opens but when I try to open a .jpg file,nothing happens.
2)Also,I cannot implement a file filter,any ideas on that?Maybe in order to load the image some other action outside the "private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)" function(as it was named by Netbeans),is required?
3)Finally I would like a short explanation about what "listener" is(like actionListener etc).I have seen it many times but I am a little bit confused about what it represents and what it does....

,I see no results.

Can you make a small, complete program for testing that compiles, executes and shows the problem?

package faerun;
import java.awt.Component;
import javax.swing.JFileChooser;
import java.io.File;
import java.awt.Desktop;
import java.io.*;
import java.awt.Graphics;

import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.event.MouseEvent;

public class Main extends javax.swing.JFrame {

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

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Preview", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 10), new java.awt.Color(0, 0, 0))); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 479, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 93, Short.MAX_VALUE)
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Action", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 10), new java.awt.Color(0, 0, 0))); // NOI18N

        jButton1.setText("Add");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Remove");

        jButton3.setText("Add");

        jButton5.setText("Add");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE)
                    .addComponent(jButton3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE)
                    .addComponent(jButton5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jButton1)
                .addGap(26, 26, 26)
                .addComponent(jButton2)
                .addGap(26, 26, 26)
                .addComponent(jButton3)
                .addGap(29, 29, 29)
                .addComponent(jButton5)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Image", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 10), new java.awt.Color(0, 0, 0))); // NOI18N

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 386, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 306, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(128, 128, 128))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

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




    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

        File file;
        BufferedImage image=null;
        JFileChooser fileChooser = new JFileChooser();

        int returnValue = fileChooser.showOpenDialog(null);
       // myfileFilter filter = new myfileFilter();
       // fileChooser.addChoosableFileFilter(filter);

        if (returnValue == JFileChooser.APPROVE_OPTION){

                System.out.println("Ok");
                //
                System.out.println("Ok");
             try{
                file=fileChooser.getSelectedFile();
                System.out.println("Selected file is "+ file);
                image=ImageIO.read(file);

               System.out.println("Ok");

               ImageIcon icon = new ImageIcon(image);
               JLabel picLabel = new JLabel(icon);

             //  picLabel.setIcon(icon);
               //picLabel.revalidate();
             //  picLabel.repaint();

               // JLabel picLabel = new JLabel(new ImageIcon(image));

               System.out.println("Ok");

               //picLabel.setIcon(icon);
               jPanel3.add(picLabel);
               jPanel3.revalidate();
               pack();
               jPanel3.repaint();
               int w = image.getWidth(null);
               int h = image.getHeight(null);
               BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);


              Graphics g = bi.getGraphics();
              g.drawImage(image,0,0,null);
                System.out.println("Ok");


        }catch(IOException e){

        }}
    }


    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });




    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    // End of variables declaration

}

Here is the full code(I tried to upload it as attachment but the file type was not allowed).Most of the code is auto-generated by Netbeans.I am basically working on the jButton1ActionPerformed function and try to solve the above problems mentioned...

If I run it the results are:

Ok
Ok
Selected file is C:\test.jpg
Ok
Ok
Ok
BUILD SUCCESSFUL (total time: 13 seconds)

but no image is Loaded nowhere

I know the code is messed up,but this is because I have tried many different methods these days and I wanted to keep them all in order to re-examine them.

One thing you should always do is have a call to the printStackTrace() method in all catch blocks.
The posted code is ignoring any exceptions with its empty catch block.

Another suggesion: Make all the print outs unique. Yours are all the same: OK
vs Ok1 , Ok2, Ok3 etc

I added e.printStackTrace(); in the catch section but I see no difference.Truth is I am new in java and have no good knowledge of exception handling.Could this be the source of my problem?I have tried several exception methods I have found while trying to implement my project,but I have seen no difference...

Adding the call to printStackTrace() wouldn't fix any problem. It would report one. It's always a good idea to add the call to all catch blocks.

package photov;

import javax.swing.*;
import javax.swing.JLabel;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFileChooser;
import java.lang.StringBuffer;
import java.lang.Object;
import java.util.*;


import javax.imageio.*;
import java.awt.image.*;
import java.io.*;
//import java.awt.GraphicsConfiguration;
//import java.awt.Dimension;
//import java.awt.BorderLayout;
//import java.awt.Color;
//import java.awt.Font;
//import javax.swing.BorderFactory;


//TODO Write Action Listener for Add Button
//http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

public class Main  {


    private static void PhotoViewerPanel(){
    final JPanel panel1 = new JPanel();
        panel1.setBorder(BorderFactory.createTitledBorder(null,"Image",
                javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
                javax.swing.border.TitledBorder.DEFAULT_POSITION,
                new Font("Tahoma", 1, 10),
                new Color(0,0,0)));
        panel1.setPreferredSize(new Dimension(0,270));

      final  JPanel panel2 = new JPanel();
        panel2.setBorder(BorderFactory.createTitledBorder(null,"Actions",
                javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
                javax.swing.border.TitledBorder.DEFAULT_POSITION,
                new Font("Tahoma", 1, 10),
                new Color(0,0,0)));
        panel2.setPreferredSize(new Dimension(150,100));

        JButton add_button = new JButton("Add");
        JButton remove_button = new JButton("Remove");

        add_button.setPreferredSize(new Dimension(80,26));
        panel2.add(add_button);
        panel2.add(remove_button);

        String fullPath;


        add_button.addActionListener(new java.awt.event.ActionListener(){
                public void actionPerformed(ActionEvent e){

                   BufferedImage image = null;
                   File file;
                   JFileChooser chooser = new JFileChooser();
                   int return_value = chooser.showOpenDialog(null);
                   if (return_value == chooser.APPROVE_OPTION){

                       file = chooser.getSelectedFile();
                       System.out.println("Selected file is "+ file);

                      String filepath = file.getAbsolutePath();
                       int i,counter=0;
                       for(i = 0; i < filepath.length(); i++){
                          if( filepath.charAt(i) == '\\' ) {
                        filepath = new StringBuffer(filepath).insert(++i, "\\").toString();

                                counter++;
                             }
                      }

                       System.out.println(counter);
                       System.out.println(filepath);

                      try{
                       image = ImageIO.read(new File(filepath));
                       }catch (IOException ex) {
                           ex.printStackTrace();
                       }
                       //Create Image at Jpanel
                      //ImageIcon icon = new ImageIcon(filepath);
                      JLabel label = new JLabel(new ImageIcon(filepath));
                      panel1.add(label,BorderLayout.CENTER);
                      panel1.repaint();

                   }

   }
       });  

        JFrame frame = new JFrame("Photo Viewer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setResizable(false);
        frame.setLocation(350, 270);
        frame.setPreferredSize(new Dimension(500,400));
        frame.setLayout(new BorderLayout());
        frame.add(panel1,BorderLayout.NORTH);
        frame.add(panel2,BorderLayout.WEST);


        frame.pack();
        frame.setVisible(true);
}


    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                PhotoViewerPanel();
            }
        });
    }
}

Here is my last effort.I tried to create everything from scratch.again no result.For example for a file like C:\test.jpg I get

Selected file is C:\test.jpg ---->After file chooser choice
1 --->Number of \ occurred in filepath
C:\test.jpg --->Doubled \ in filepath.I did this because I ran another web example and when there was only 1 \ in the path,it could not display the image.

Please help,how can I draw the image inside my jpanel?I have tried very much but maybe there is something I don't get.

Why all that messing about with the path? Why not go straight through like this

file = chooser.getSelectedFile();
image = ImageIO.read(file);

As I wrote in the end, I tested another web example at some point,which used an absolute path as a parameter.When that absolute path contained a single \,the image was not displayed.When I added another \,the image displayed correctly.Here is the example

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package loadimageapp;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

/**
 * This class demonstrates how to load an Image from an external file
 */
public class Main extends Component {

    BufferedImage img;

    public void paint(Graphics g) {
        g.drawImage(img, 0, 0, null);
    }

    public Main() {
       try {
           img = ImageIO.read(new File("C:\\test.jpg"));
       } catch (IOException e) {
       }

    }

    public Dimension getPreferredSize() {
        if (img == null) {
             return new Dimension(100,100);
        } else {
           return new Dimension(img.getWidth(null), img.getHeight(null));
       }
    }

    public static void main(String[] args) {

        JFrame f = new JFrame("Load Image Sample");

        f.addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });

        f.add(new Main());
        f.pack();
        f.setVisible(true);
    }
}

That's because \ is a special character in Java literal strings (eg \n). If you want a single \ you need to code it as two \ so it's not taken as a special character.

\ is a special character in a String literal. When used with one of a small group of other characters they represent a character that can not be entered easily from the keyboard. For example: \n is the new line character. \t is the tab character. If you want the char \ in a String literal you need to code: "\\" That tells the compiler to put a \ into the String.

So my effort to create C:\test.jpg with double \ instead of C:\test.jpg with just one \ is useless?Except from that,any idea why my program does not display the photo in the jpanel?

One problem I see with your code is an empty catch block. You should ALWAYS call the printStackTrace() method in catch blocks.

The posted code works for me when I change the call to File to a file on my PC:

           img = ImageIO.read(new File("images/duke.gif"));

the loadimageapp is not my code,I just posted to show a code that works.My code is the one named after "photov".Are you referring to that code?

I was refering to the last post: package loadimageapp
That is the one I copied the changed statement from.

When you change the contents of a container you need to tell it to redo its layout. There are methods in the Container class that have to do with layouts: invalidate() and validate() for example.
Try some of them.

ok problem solved!!I did one or two addition and I guess the most important was revalidate addition.Now in order to fully complete the 'look' part I would like two things:

1)How can I make the frame to be size-independent(for example if I maximize the window,I want every component and image to resize in a correct manner)
2)How can I scale the created image to fit exactly in the jpanel that I created especially for image display on my jframe.

I already began to search.I would be glad to receive any recommondations :)

  1. Use a LayoutManager to organise your window. It will handle re-sizing. For the best possible control of how that happens use a GridBagLayout.
  2. You can query the size of your JPanel, then use the Image getScaledInstance method to convert your image to the right size.
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.