Results 1 to 10 of 10
  1. #1
    javaexplorer is offline Member
    Join Date
    Jan 2010
    Posts
    20
    Rep Power
    0

    Question Can't show images onto the screen

    Hi All,

    I am new to Java and am trying to build a small program to display the images corresponding to an item selected by the user from the list. The problem I am facing is the overridden paintComponent method in a subclass of JPanel never gets called and so the images are never shown on the screen.

    Any help that you can provide to solve this problem would be greatly appreciated. I am re-producing here the entire code listing for your reference (sorry for it being little long).

    Java Code:
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.JPanel;
    
    import java.awt.Dimension;
    
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    
    
    /**
     *
     * This is an application to view images for the various known hardware problems for the selected
     * make of the phone.
     */
    public class PhoneFaultFixer extends javax.swing.JFrame {
    
        /** Creates new form PhoneFaultFixer */
        public PhoneFaultFixer() {
            initComponents();
    
            GlobalVariables.imagesContainer = this.imagesContainer;
            
            //populate the list
            jList1.setModel(new javax.swing.AbstractListModel() {
                String[] strings = { "Nokia", "Samsung", "LG"};
                public int getSize() { return strings.length; }
                public Object getElementAt(int i) { return strings[i]; }
            });
    
            //set that the user can only select one item from the list.
            jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
            
            //register an itemchange listener
            jList1.addListSelectionListener(new MyListSelectionListener());
        }
    
        /** 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() {
    
            jLabel1 = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            jList1 = new javax.swing.JList();
            jLabel2 = new javax.swing.JLabel();
            jScrollPane2 = new javax.swing.JScrollPane();
            imagesContainer = new javax.swing.JPanel();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Phone Fault Fixer");
    
            jLabel1.setText("Phone make:");
    
            jList1.setModel(new javax.swing.AbstractListModel() {
                String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
                public int getSize() { return strings.length; }
                public Object getElementAt(int i) { return strings[i]; }
            });
            jScrollPane1.setViewportView(jList1);
    
            jLabel2.setText("Faults for the phone make selected:");
    
            javax.swing.GroupLayout imagesContainerLayout = new javax.swing.GroupLayout(imagesContainer);
            imagesContainer.setLayout(imagesContainerLayout);
            imagesContainerLayout.setHorizontalGroup(
                imagesContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 469, Short.MAX_VALUE)
            );
            imagesContainerLayout.setVerticalGroup(
                imagesContainerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 231, Short.MAX_VALUE)
            );
    
            jScrollPane2.setViewportView(imagesContainer);
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel1)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(61, 61, 61)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel2)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 471, Short.MAX_VALUE))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(22, 22, 22)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 233, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(28, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>                        
    
        /**
        * @param args the command line arguments
        */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    GlobalVariables.topContainer = new PhoneFaultFixer();
                    GlobalVariables.topContainer.setVisible(true);
                }
            });
        }
    
        // Variables declaration - do not modify                     
        private javax.swing.JPanel imagesContainer;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JList jList1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JScrollPane jScrollPane2;
        // End of variables declaration                   
    
    
    
    }// end of class declaration for PhoneFaultFixer
    
    class MyListSelectionListener implements ListSelectionListener {
    
     public void valueChanged(ListSelectionEvent e)  {
    
         //process only if the selection has been done
         if (e.getValueIsAdjusting()) return;
    
       //Extract the phone make selected by the user
       GlobalVariables.phoneMake =  (String) ((javax.swing.JList) e.getSource()).getSelectedValue();
        
       
        new ImageLoader().loadImages(); //show the images corresponding to the selection
      
       
       
     }  //end of definition for valueChanged
    
     
    } //end of definition for ListSelectionListener
    
    //class to hold global varibles
    class GlobalVariables {
        
        static javax.swing.JFrame topContainer;
        static String phoneMake;
        static final String rootPath = "E:\\My Documents\\";
        static javax.swing.JPanel imagesContainer;
        
    } // end of the definition for the class GlobalVariables
    
    class ImageLoader implements java.io.FilenameFilter {
    
        public void loadImages()  {
    
         //get the path of all image files corresponding to the selected phone make
         String[] imagesPaths = getImagesPaths();
    
        String lookupFolder = GlobalVariables.rootPath +
                GlobalVariables.phoneMake;
        String fullPath;
        BufferedImage image;
    
         //remove all existing components from the imagesContainer
         GlobalVariables.imagesContainer.removeAll();
    
         //display each image file on the screen
        for(int i = 0; i < imagesPaths.length; i++) {
                              
            //Read the image file from the storage medium
          image = null;
          fullPath = lookupFolder + "\\" + imagesPaths[i];
         
          try {
           image = ImageIO.read(new File(fullPath));
           }
           catch (java.io.IOException ioex) {
               System.err.println("The message is: " + 
                       ioex.getMessage() + ", and the error" +
                       " class is " + ioex.getClass().getName());
               ioex.printStackTrace();
               return;
           } catch (Exception ex) {
                   System.err.println("The message is: " + 
                       ex.getMessage() + ", and the error" +
                       " class is " + ex.getClass().getName());
                   return;
           }
       
          ImageHolder imageContainer = new ImageHolder(image);
          imageContainer.setPreferredSize(new Dimension(200, 200));
    
            // add the Jpanel holding an image to a container
            GlobalVariables.imagesContainer.add(imageContainer);
            imageContainer.setVisible(true);
            
        } // end of for loop construct
    
         
         GlobalVariables.imagesContainer.setVisible(true);
         GlobalVariables.imagesContainer.revalidate();
         
    
        }//end of LoadImages method
         
         private String[] getImagesPaths() {
    
            // returns the names of all the image files found in the folder
            //corresponding to the phone make selected by the user.
    
            String lookupFolder = GlobalVariables.rootPath + GlobalVariables.phoneMake;
            //get the path of all images files in the lookupFolder
            String[] imagesPaths = new File(lookupFolder).list(this);
    
            return imagesPaths;
        } // end of the definition for getImagesPaths
    
         public boolean accept(File dir, String name) {
    
             //return true if only the file extension is ".jpg"
    
             
             //extract the file extension
             int index = name.indexOf('.');
             String fileExtension = name.substring(index + 1);
    
             if (fileExtension.equalsIgnoreCase("jpg") ||
                     fileExtension.equalsIgnoreCase("png"))
                 return true;
             else
                 return false;
    
             
         } //end of definition for accept method
    
    } //end of the definition for ImageLoader
    
    class ImageHolder extends JPanel {
        
        BufferedImage faultImage;    
       
        public ImageHolder (BufferedImage faultImage) {
            this.faultImage = faultImage;
        }
        
         protected void paintComponent(java.awt.Graphics g) {
           
             super.paintComponent(g);
    
             g.drawImage(faultImage, 0, 0, this);
       
            
         }
    
        
    } // end of the definition for ImageHolder
    Last edited by Fubarable; 01-12-2010 at 07:37 PM. Reason: code tags added

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    First off, welcome to the forum!

    Next off, I added code tags to your post above to help make your code more readable. Please read my signature below to learn how to do this yourself.

    Thirdly, your code uses NetBeans code generation which means that many here can't run it (and which makes it harder to read the layout and see what's wrong). I recommend that you try to recode this in a very simple fashion without the code generation to see what happens and to post smaller more readable code here.

    Fourthly, I wonder if the ImagePanel that holds the image is even being displayed. I haven't poured through all of your code, but I am concerned if this JPanel is being replaced by another. I recommend that you put a colored border around it by calling setBorder(BorderFactor.createLineBorder(Color.blue )); or a titled border to see if it is even being displayed.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Change your ImageHolder class to this:
    Java Code:
    class ImageHolder extends JPanel {
    
      BufferedImage faultImage;
    
      public ImageHolder(BufferedImage faultImage) {
        this.faultImage = faultImage;
        setBorder(BorderFactory.createTitledBorder("Image Holder"));
      }
    
      protected void paintComponent(java.awt.Graphics g) {
        super.paintComponent(g);
        g.drawImage(faultImage, 0, 0, this);
        System.out.println("paintComponent called?");
      }
    
    }
    and you'll likely see that your never rendering an object of this type. I think you're creating an object of this type, but never placing it anywhere where it is going to be visualized, probably because you swap it out for another JPanel or else update a variable but don't update the actual object held by the GUI.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    More,...

    here:
    Java Code:
        GlobalVariables.imagesContainer = this.imagesContainer;
    you appear to be overwriting the container that is supposed to hold the image panel. Also, what's with these global variables and statics?

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Hm, looks like you disappeared... I'm not sure if you're still having a problem or not, but if so, one possible change that I would make if this were my program would be to make my ImageHolder JPanel be able to change images that it draws. So rather than try to swap image holder jpanels or any jpanels, simply change the image. For instance, something like this:

    Java Code:
    @SuppressWarnings("serial")
    class ImageHolder2 extends JPanel {
      private Image image = null;
      
      public void setImage(Image image) {
        this.image = image;
        repaint();
      }
      
      @Override
      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image != null) {
          g.drawImage(image, 0, 0, this);
        }
      }
    }
    Please let us know if any of these suggestions make sense or not, and if they help or not.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    I can't seem to leave this thread alone.

    I'm now thinking, what the heck, you don't even need an ImageHolder JPanel because if all you want to do is have it show and swap images, then shoot, just use a JLabel and swap ImageIcons. For example:
    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Image;
    import java.io.IOException;
    import java.net.URL;
    
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.event.*;
    
    public class DukeImageDisplayer {
      private static final String[][] ITEMS = {
        {"Vote", "http://duke.kenai.com/misc/Vote.png"},
        {"Bullfight", "http://duke.kenai.com/misc/Bullfight.jpg"},
        {"Glassfish", "http://duke.kenai.com/glassfish/GlassFishMedium.jpg"}
      };
      private static final Dimension IMAGE_HOLDER_SIZE = new Dimension(700, 500);
      private JPanel mainPanel = new JPanel();
      private DefaultListModel model = new DefaultListModel();
      private JList itemList = new JList(model);
      //private ImageHolder2 imageHolder = new ImageHolder2();
      private JLabel imageHolder = new JLabel();
    
      public DukeImageDisplayer() {
        for (String[] item : ITEMS) {
          ImageItem imageitem;
          try {
            URL url = new URL(item[1]);
            imageitem = new ImageItem(item[0], url);
            model.addElement(imageitem);
          } catch (IOException e) {
            System.out.println("Images unreadable.  To exit");
            System.exit(1);
          }
        }
        
        imageHolder.setPreferredSize(IMAGE_HOLDER_SIZE);
        imageHolder.setHorizontalAlignment(SwingConstants.CENTER);
        
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        mainPanel.setLayout(new BorderLayout(25, 25));
        mainPanel.add(createWestPanel(), BorderLayout.WEST);
        mainPanel.add(createCenterPanel(), BorderLayout.CENTER);
      }
    
      private JPanel createCenterPanel() {
        JPanel centerPanel = new JPanel(new BorderLayout(5, 5));
        centerPanel.add(new JLabel("Duke Image:", SwingConstants.LEFT ), BorderLayout.NORTH);
        centerPanel.add(new JScrollPane(imageHolder), BorderLayout.CENTER);
        return centerPanel;
      }
    
      private JPanel createWestPanel() {
        itemList.addListSelectionListener(new ListSelectionListener() {
    
          public void valueChanged(ListSelectionEvent lsEvent) {
            ImageIcon icon = ((ImageItem)itemList.getSelectedValue()).getIcon();
            imageHolder.setIcon(icon);
          }     
        });
        
        JPanel westCenterPanel = new JPanel(new BorderLayout());
        westCenterPanel.add(new JScrollPane(itemList), BorderLayout.NORTH);
        westCenterPanel.add(new JLabel(), BorderLayout.CENTER);
        
        JPanel westPanel = new JPanel(new BorderLayout(5, 5));
        westPanel.add(new JLabel("Duke Image Title:", SwingConstants.LEFT ), BorderLayout.NORTH);
        westPanel.add(westCenterPanel, BorderLayout.CENTER);
        
        return westPanel;
      }
    
      public JComponent getPanel() {
        return mainPanel;
      }
      private static void createAndShowGUI() {
        JFrame frame = new JFrame("Duke Images");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new DukeImageDisplayer().getPanel());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
          }
        });
      }
    }
    
    class ImageItem {
      private String name;
      private ImageIcon icon;
      public ImageItem(String name, URL url) throws IOException {
        this.name = name;
        
        Image image = ImageIO.read(url);
        if (image != null) {
          icon = new ImageIcon(image);
        }
      }
      public ImageIcon getIcon() {
        return icon;
      }
    
      public String getName() {
        return name;
      }
      
      @Override
      public String toString() {
        return name;
      }
    }

  7. #7
    javaexplorer is offline Member
    Join Date
    Jan 2010
    Posts
    20
    Rep Power
    0

    Default

    Hi Fubarable,

    Many thanks for your replies.

    I am totally awed by the promptness of your replies and your willingness to assist me. Given the nature of your help, I am inclined to think that this must be one of the best Java forums around.

    With regards to the issue posted, I have figured out that that the images weren't not getting displayed as I had not specified the layout instructions to the JPanel's layout manager. I was actually misled by the Sun's Java tutorial, which said that a JPanel, by default, uses the FlowLayout layout manager, but it turns out that it actually uses the GroupLayout layout manager. I changed the layout to FlowLayout and the images are now showing without any other change to the code.

    However, I am now facing another problem as the images shown on the selection of an item from the list are not getting removed on the selection of another item from the list. For example, if there are 3 images corresponding to the list item "Nokia" and 1 image to the item "LG", and if I select "Nokia" first, it correctly displays 3 images and now if I select "LG", it continues to show 3 images,though the first image is replaced by an LG phone image.

    Could you suggest what needs to be done to overcome this problem.

    Many Thanks.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by javaexplorer View Post
    Many thanks for your replies.
    I am totally awed by the promptness of your replies and your willingness to assist me. Given the nature of your help, I am inclined to think that this must be one of the best Java forums around.
    You are quite welcome!

    With regards to the issue posted, I have figured out that that the images weren't not getting displayed as I had not specified the layout instructions to the JPanel's layout manager. I was actually misled by the Sun's Java tutorial, which said that a JPanel, by default, uses the FlowLayout layout manager, but it turns out that it actually uses the GroupLayout layout manager. I changed the layout to FlowLayout and the images are now showing without any other change to the code.
    Not so. JPanels do use FlowLayout by default! But things change when you use NetBeans to generate your code. If you look at the code generated by NetBeans, you'll see that it's changing your JPanel's layout by setting it to GroupLayout. This is one of many reasons I recommend against using NetBeans generated code.

    However, I am now facing another problem as the images shown on the selection of an item from the list are not getting removed on the selection of another item from the list. For example, if there are 3 images corresponding to the list item "Nokia" and 1 image to the item "LG", and if I select "Nokia" first, it correctly displays 3 images and now if I select "LG", it continues to show 3 images,though the first image is replaced by an LG phone image.
    Could you suggest what needs to be done to overcome this problem.
    To know what you're doing wrong requires code. I suggest that you create and post an SSCCE (please see the link).

  9. #9
    javaexplorer is offline Member
    Join Date
    Jan 2010
    Posts
    20
    Rep Power
    0

    Default

    Thanks for clarifying my misconception regarding the default layout manager for JPanels. And, my sorry to the person who authored the Sun's Java Tutorial. :o

    However, I am now facing another problem as the images shown on the selection of an item from the list are not .....
    Well, this problem has been resolved after I invoked repaint method on JPanel after removing all its components.

    Also, I will endeavor to post all future codes by adhering to SSCCE guidelines. :)

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by javaexplorer View Post
    Thanks for clarifying my misconception regarding the default layout manager for JPanels. ...
    And you're welcome.
    Well, this problem has been resolved after I invoked repaint method on JPanel after removing all its components.
    Wonderful!

    Also, I will endeavor to post all future codes by adhering to SSCCE guidelines. :)
    It's certainly not a requirement, but it will likely help you get decent help faster. Best of luck!

Similar Threads

  1. new screen
    By tha_crazy in forum New To Java
    Replies: 4
    Last Post: 02-16-2011, 11:46 AM
  2. Blank Screen while navigating from one screen to another
    By mohana.krishna in forum Java Servlet
    Replies: 0
    Last Post: 03-03-2009, 06:03 PM
  3. netbeans 6.0 not show commpunent or show blank page
    By fahimaamir in forum NetBeans
    Replies: 1
    Last Post: 01-26-2008, 07:20 AM
  4. Problems to show images in applets
    By Felissa in forum Java Applets
    Replies: 1
    Last Post: 07-06-2007, 10:12 PM
  5. Full screen
    By Jack in forum Advanced Java
    Replies: 2
    Last Post: 07-02-2007, 06:49 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •