Results 1 to 3 of 3
  1. #1
    aneesahamedaa is offline Member
    Join Date
    Jul 2008
    Posts
    26
    Rep Power
    0

    Default How do I display a JList with icons and text?

    How can I have the components displayed while executing the given code, as JList elements.
    What I have done in this code is that, I have created different JPanels and to those JPanels, added an icon with a corresponding name, and finally added all these JPanels to a main JPanel(as you can see from the code).
    I am looking for JList alternative instead of JPanels for the reason that, I want to select/deselect these icons as in a windows explorer, which I think, is possible with a JList. How to modify this code such that I can achieve this? The alignment of the icons should be like that in current code.
    Any help is greatly appreciated.

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Image;
    import java.awt.Insets;
    import java.awt.event.MouseAdapter;
    import java.io.File;
    import java.io.IOException;
    import java.lang.reflect.Method;
    import java.util.Vector;
     
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JViewport;
    import javax.swing.SwingConstants;
    import javax.swing.UIManager;
    import javax.swing.filechooser.FileSystemView;
     
    import sun.awt.shell.ShellFolder;
     
    public class ScrollableWrapTest {
        public static void main(String[] args) {
            try {
                     ScrollableWrapTest st = new ScrollableWrapTest();
                final JPanel mainPanel = new JPanel(new WrapScollableLayout(FlowLayout.LEFT, 10, 10));
                mainPanel.setBackground(Color.WHITE);
                JScrollPane pane = new JScrollPane(mainPanel);
                pane.setPreferredSize(new Dimension(550, 300));
                Vector v = new Vector();
                v.add("first.doc");
                v.add("second.txt");
                v.add("third.pdf");
                v.add("fourth.rar");
                v.add("fifth.zip");
                v.add("sixth.folder");
                v.add("seventh.exe");
                v.add("eighth.bmp");
                v.add("nineth.jpeg");
                v.add("tenth.wav");
               
                
                JLabel img = null;
                for(int i =0;i<v.size();i++){
                    JPanel panel = new JPanel(new BorderLayout());
                    Icon icon = st.getIcone(st.getExtension(v.elementAt(i).toString().toUpperCase()));
                            panel.setBackground(Color.WHITE);
                        
                        img = new JLabel(icon);
                        img.setBackground(Color.WHITE);
                        JPanel buttonPanel = new JPanel();
                        buttonPanel.setBackground(Color.WHITE);
                        buttonPanel.add(img);
                                            
                        JLabel label = new JLabel((String)v.elementAt(i));
                        
                        label.setHorizontalAlignment(SwingConstants.CENTER);
                        label.setSize(new Dimension(5,5));
                                            
                        panel.add(buttonPanel , BorderLayout.NORTH);
                        panel.add(label, BorderLayout.SOUTH);
                        panel.addMouseListener(new MouseAdapter(){});
                        mainPanel.add(panel);
                        mainPanel.addMouseListener(new MouseAdapter(){
                            
                        });
                    mainPanel.revalidate();
            }
               
                st.buildGUI(pane);
                
            } catch (Exception e) {e.printStackTrace();}
        }
        public void buildGUI(JScrollPane scrollPane)
        {
            JFrame frame = new JFrame("Scrollable Wrap Test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(scrollPane, BorderLayout.CENTER);
            frame.setLocationRelativeTo(null);
            frame.pack();
            frame.setVisible(true);
          }
        public String getExtension(String name)
            {
                    if(name.lastIndexOf(".")!=-1)
                    {
                            String extensionPossible = name.substring(name.lastIndexOf(".")+1, name.length());
                            if(extensionPossible.length()>6)
                            {
                                    return "";
                            }
                            else 
                            {
                                    return extensionPossible;
                            }
                    }
                    else return "";
            }
            public Icon getIcone(String extension)
            {
                    File file;
                    String cheminIcone = "";
                    if(((System.getProperties().get("os.name").toString()).startsWith("Mac")))
                            cheminIcone = System.getProperties().getProperty("file.separator");
                    else if(((System.getProperties().get("os.name").toString()).startsWith("Linux")))
                            cheminIcone = "/"+"tmp"+"/BoooDrive-"+System.getProperty("user.name")+"/";
                    else cheminIcone = System.getenv("TEMP") + System.getProperties().getProperty("file.separator");
                    
                    File repIcone = new File(cheminIcone);
                    if(!repIcone.exists()) repIcone.mkdirs();
                    
                    try
                    {
                            if(extension.equals("FOLDER"))
                            {
                                    file = new File(cheminIcone + "icon");
                                    file.mkdir();
                            }
     
     
                            else
                            {
                                    file = new File(cheminIcone + "icon." + extension.toLowerCase());
                                    file.createNewFile();
                            }
                            
                            Icon icone = getSystemIcon(file);
                            
                            file.delete();
                            return icone;
                    } 
                    catch (IOException e){ }
                    return null;
            }
            public static Icon getSystemIcon(File f) {
                if (f != null) {
                    Class fsv = FileSystemView.class;
                    try {
                        Method m = fsv.getDeclaredMethod("getShellFolder", new Class[]{File.class});
                        m.setAccessible(true);
                        ShellFolder sf = (ShellFolder) m.invoke(FileSystemView.getFileSystemView(), f);
                        Image img = sf.getIcon(true);
                        if (img != null) {
                            return new ImageIcon(img, sf.getFolderType());
                        } else {
                            return UIManager.getIcon(f.isDirectory() ? "FileView.directoryIcon" : "FileView.fileIcon");
                        }
                    } catch (Exception e) {e.printStackTrace();}
                } 
                return null;
            }
     
        private static class WrapScollableLayout extends FlowLayout {
            public WrapScollableLayout(int align, int hgap, int vgap) {
                super(align, hgap, vgap);
            }
            
            public Dimension preferredLayoutSize(Container target) {
                synchronized (target.getTreeLock()) {
                    Dimension dim = super.preferredLayoutSize(target);
                    layoutContainer(target);
                    int nmembers = target.getComponentCount();
                    for (int i = 0 ; i < nmembers ; i++) {
                        Component m = target.getComponent(i);
                        if (m.isVisible()) {
                            Dimension d = m.getPreferredSize();
                            dim.height = Math.max(dim.height, d.height + m.getY());
                        }
                    }
                    if (target.getParent() instanceof JViewport)
                        dim.width = ((JViewport) target.getParent()).getExtentSize().width;
                    Insets insets = target.getInsets();
                    dim.height += insets.top + insets.bottom + getVgap();
                    return dim;
                }
            }
        }
    }

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

    Default

    You'll want to create your own renderer for the JList, one that uses a JPanel for instance. Have a look at the JList class's and the ListCellRenderer interface's API as well as the list tutorial:

    JList (Java Platform SE 6)
    ListCellRenderer (Java Platform SE 6)
    How to Use Lists (The Javaô Tutorials > Creating a GUI with JFC/Swing > Using Swing Components)

  3. #3
    aneesahamedaa is offline Member
    Join Date
    Jul 2008
    Posts
    26
    Rep Power
    0

    Default

    I am cut - shorting my question so that things would be more easy. Please read the modified question, based on the efforts I made.

    I need to have a Jlist with the appearance given in this link.
    //docs.google.com/Doc?id=dfzrknk_13d84m6hgg
    For this, as the first step, I created the below given class.
    Java Code:
    import java.awt.Color;
    import java.util.Vector;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.ListModel;
    
    public class ListTest{
        public static void main(String[] args) {
        Vector v = new Vector();
         v.add("first.doc");
         v.add("second.txt");
         v.add("third.pdf");
         v.add("fourth.rar");
         v.add("fifth.zip");
         v.add("sixth.folder");
         v.add("seventh.exe");
         v.add("eighth.bmp");
         v.add("nineth.jpeg");
         v.add("tenth.wav");
              
         JList myList = new JList(v);
         JFrame f = new JFrame("ListTest");
         f.getContentPane().setBackground(Color.WHITE);
         f.getContentPane().add( myList);
         f.setSize(300,300);
         f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
         f.setVisible(true);
        
         ListModel model = myList.getModel();
         for(int i = 0; i < model.getSize(); i++) {
             System.out.println(model.getElementAt(i));
         }
         myList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
    }
    }
    I have a method to get the system icons for file names based on their extension. If you give abc.doc to this method, it will return a doc icon.
    This is the method.

    Java Code:
    public String getExtension(String name)
        {
            if(name.lastIndexOf(".")!=-1)
            {
                String extensionPossible = name.substring(name.lastIndexOf(".")+1, name.length());
                if(extensionPossible.length()>6)
                {
                    return "";
                }
                else
                {
                    return extensionPossible;
                }
            }
            else return "";
        }
        public Icon getIcone(String extension)
        {
            File file;
            String cheminIcone = "";
            if(((System.getProperties().get("os.name").toString()).startsWith("Mac")))
                cheminIcone = System.getProperties().getProperty("file.separator");
            else if(((System.getProperties().get("os.name").toString()).startsWith("Linux")))
                cheminIcone = "/"+"tmp"+"/BoooDrive-"+System.getProperty("user.name")+"/";
            else cheminIcone = System.getenv("TEMP") + System.getProperties().getProperty("file.separator");
            
            File repIcone = new File(cheminIcone);
            if(!repIcone.exists()) repIcone.mkdirs();
            
            try
            {
                if(extension.equals("FOLDER"))
                {
                    file = new File(cheminIcone + "icon");
                    file.mkdir();
                }
                else
                {
                    file = new File(cheminIcone + "icon." + extension.toLowerCase());
                    file.createNewFile();
                }
                
                Icon icone = getSystemIcon(file);
                
                file.delete();
                return icone;
            }
            catch (IOException e){ }
            return null;
        }
        public static Icon getSystemIcon(File f) {
            if (f != null) {
                Class fsv = FileSystemView.class;
                try {
                    Method m = fsv.getDeclaredMethod("getShellFolder", new Class[]{File.class});
                    m.setAccessible(true);
                    ShellFolder sf = (ShellFolder) m.invoke(FileSystemView.getFileSystemView(), f);
                    Image img = sf.getIcon(true);
                    if (img != null) {
                        return new ImageIcon(img, sf.getFolderType());
                    } else {
                        return UIManager.getIcon(f.isDirectory() ? "FileView.directoryIcon" : "FileView.fileIcon");
                    }
                } catch (Exception e) {e.printStackTrace();}
            }
            return null;
        }
    By using this method for getting icons, how can I add an icon on top of each of those JList elements in my current class?
    Kindly help with code.
    Regards,
    Anees

Similar Threads

  1. Replies: 17
    Last Post: 07-13-2009, 06:44 AM
  2. Replies: 0
    Last Post: 06-28-2008, 10:26 PM
  3. Displaying a Button with Varying Icons
    By Java Tip in forum javax.swing
    Replies: 0
    Last Post: 06-26-2008, 08:40 PM
  4. How to display scrolling text and image on a JFrame
    By Abhi_vk in forum AWT / Swing
    Replies: 1
    Last Post: 06-20-2008, 11:19 PM
  5. Moving icons on your desktop
    By Leprechaun in forum New To Java
    Replies: 3
    Last Post: 12-14-2007, 11:07 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
  •