Results 1 to 10 of 10
- 01-12-2010, 06:30 PM #1
Member
- Join Date
- Jan 2010
- Posts
- 20
- Rep Power
- 0
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 ImageHolderLast edited by Fubarable; 01-12-2010 at 06:37 PM. Reason: code tags added
-
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.
-
Change your ImageHolder class to this:
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.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?"); } }
-
More,...
here:
you appear to be overwriting the container that is supposed to hold the image panel. Also, what's with these global variables and statics?Java Code:GlobalVariables.imagesContainer = this.imagesContainer;
-
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:
Please let us know if any of these suggestions make sense or not, and if they help or not.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); } } }
-
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; } }
- 01-14-2010, 06:44 AM #7
Member
- Join Date
- Jan 2010
- Posts
- 20
- Rep Power
- 0
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.
-
You are quite welcome!
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.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.
To know what you're doing wrong requires code. I suggest that you create and post an SSCCE (please see the link).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.
- 01-14-2010, 04:43 PM #9
Member
- Join Date
- Jan 2010
- Posts
- 20
- Rep Power
- 0
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
Well, this problem has been resolved after I invoked repaint method on JPanel after removing all its components.However, I am now facing another problem as the images shown on the selection of an item from the list are not .....
Also, I will endeavor to post all future codes by adhering to SSCCE guidelines. :)
-
And you're welcome.
Wonderful!Well, this problem has been resolved after I invoked repaint method on JPanel after removing all its components.
It's certainly not a requirement, but it will likely help you get decent help faster. Best of luck!Also, I will endeavor to post all future codes by adhering to SSCCE guidelines. :)
Similar Threads
-
new screen
By tha_crazy in forum New To JavaReplies: 4Last Post: 02-16-2011, 10:46 AM -
Blank Screen while navigating from one screen to another
By mohana.krishna in forum Java ServletReplies: 0Last Post: 03-03-2009, 05:03 PM -
netbeans 6.0 not show commpunent or show blank page
By fahimaamir in forum NetBeansReplies: 1Last Post: 01-26-2008, 06:20 AM -
Problems to show images in applets
By Felissa in forum Java AppletsReplies: 1Last Post: 07-06-2007, 09:12 PM -
Full screen
By Jack in forum Advanced JavaReplies: 2Last Post: 07-02-2007, 05:49 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks