Results 1 to 8 of 8

Thread: JList issues

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

    Default JList issues

    Hi all,
    In the attached code, I need to have the following options
    1) get the name(eg;first.doc) of the selected item/items.
    2) When I right click on top of a particular item, I need to have that item alone selected.
    3) I need to have no selection for elements once I click outside the list.
    I am attaching the code I developed, here.
    Kindly help implementing these.
    Any help is greatly appreciated.
    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Image;
    import java.io.File;
    import java.io.IOException;
    import java.lang.reflect.Method;
    import javax.swing.DefaultListCellRenderer;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.ListCellRenderer;
    import javax.swing.UIManager;
    import javax.swing.filechooser.FileSystemView;
    
    import sun.awt.shell.ShellFolder;
     
    public class MainClass {
      public static void main(String args[]) throws Exception {
             
        MainClass mc = new MainClass();
             Object elements[][] = { {"first.doc",mc.getIcone(mc.getExtension("first.doc".toUpperCase()))},
                                                              {"second.pdf",mc.getIcone(mc.getExtension("second.pdf".toUpperCase()))},      
                                                              {"third.txt",mc.getIcone(mc.getExtension("third.txt".toUpperCase()))} ,
                                                              {"first.doc",mc.getIcone(mc.getExtension("first.doc".toUpperCase()))},
                                                              {"second.pdf",mc.getIcone(mc.getExtension("second.pdf".toUpperCase()))},      
                                                              {"third.txt",mc.getIcone(mc.getExtension("third.txt".toUpperCase()))} 
              
              
              };
              
    
        JFrame frame = new JFrame("Trial");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
        JList jlist = new JList(elements);
        ListCellRenderer renderer = new ComplexCellRenderer();
        jlist.setCellRenderer(renderer);
        jlist.setLayoutOrientation(JList.HORIZONTAL_WRAP);
        jlist.setVisibleRowCount(-1);
        JScrollPane scrollPane = new JScrollPane(jlist);
        frame.add(scrollPane, BorderLayout.CENTER);
     
        frame.setSize(300, 200);
        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;
            }
     
    }
     
    class ComplexCellRenderer implements ListCellRenderer {
      protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
     
      public Component getListCellRendererComponent(JList list, Object value, int index,
          boolean isSelected, boolean cellHasFocus) {
        Icon icon = null;
        String theText = null;
     
        JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index,
            isSelected, cellHasFocus);
        renderer.setVerticalTextPosition(JLabel.BOTTOM);
        renderer.setHorizontalTextPosition(JLabel.CENTER);
    
     
        if (value instanceof Object[]) {
          Object values[] = (Object[]) value;
          theText = (String) values[0];
          icon = (Icon) values[1];
        } else {
          
        }
        renderer.setText(theText);
        renderer.setIcon(icon);
        return renderer;
      }
    }

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

    Default

    Please provide help.

  3. #3
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Click in the south textField to remove focus from the JList.
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.lang.reflect.Method;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.filechooser.FileSystemView;
    
    import sun.awt.shell.ShellFolder;
    
    public class MC {
        public static void main(String[] args) throws Exception {
    
            MC mc = new MC();
            Object[][] elements = {
                { "first.doc",
                   mc.getIcone(mc.getExtension("first.doc".toUpperCase()))  },
                { "second.pdf",
                   mc.getIcone(mc.getExtension("second.pdf".toUpperCase())) },
                {"third.txt",
                   mc.getIcone(mc.getExtension("third.txt".toUpperCase()))  },
                {"first.doc",
                   mc.getIcone(mc.getExtension("first.doc".toUpperCase()))  },
                {"second.pdf",
                   mc.getIcone(mc.getExtension("second.pdf".toUpperCase())) },
                {"third.txt",
                   mc.getIcone(mc.getExtension("third.txt".toUpperCase()))  }
            };
    
            JFrame frame = new JFrame("Trial");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            JList jlist = new JList(elements);
            ListCellRenderer renderer = new ComplexCellRenderer();
            jlist.setCellRenderer(renderer);
            jlist.setLayoutOrientation(JList.HORIZONTAL_WRAP);
            jlist.setVisibleRowCount(-1);
            // 2) When I right click on top of a particular item,
            //    I need to have that item alone selected.
            jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            // 1) get the name (eg, first.doc) of the selected item
            jlist.addListSelectionListener(new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent e) {
                    if(!e.getValueIsAdjusting()) {
                        Object value = ((JList)e.getSource()).getSelectedValue();
                        if(value != null) {
                            String name = (String)((Object[])value)[0];
                            System.out.println("name = " + name);
                        }
                    }
                }
            });
            // 3) I need to have no selection for elements once
            //    I click outside the list.
            jlist.addFocusListener(new FocusAdapter() {
                public void focusLost(FocusEvent e) {
                    ((JList)e.getSource()).clearSelection();
                }
            });
            JScrollPane scrollPane = new JScrollPane(jlist);
            frame.add(scrollPane, BorderLayout.CENTER);
            frame.add(new JTextField(), BorderLayout.SOUTH);
    
            frame.setSize(300, 200);
            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;
        }
    
        @SuppressWarnings("unchecked")
        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;
        }
    }
    
    class ComplexCellRenderer implements ListCellRenderer {
        protected DefaultListCellRenderer defaultRenderer =
            new DefaultListCellRenderer();
    
        public Component getListCellRendererComponent(JList list, Object value,
                    int index, boolean isSelected, boolean cellHasFocus) {
            Icon icon = null;
            String theText = null;
    
            JLabel renderer =
                (JLabel) defaultRenderer.getListCellRendererComponent(list,
                             value, index, isSelected, cellHasFocus);
            renderer.setVerticalTextPosition(JLabel.BOTTOM);
            renderer.setHorizontalTextPosition(JLabel.CENTER);
    
            if (value instanceof Object[]) {
                Object[] values = (Object[]) value;
                theText = (String) values[0];
                icon = (Icon) values[1];
            } else {
                System.out.println("value = " + value.toString());
            }
            renderer.setText(theText);
            renderer.setIcon(icon);
            return renderer;
        }
    }

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

    Default

    Thanks alot.
    That was an awesome work hardwired.
    Also,
    How can I reduce the width of the selected item.
    Just see the link JList Selected Area
    I need to somehow reduce the width of the selected area. What should be done?
    Anees
    Last edited by aneesahamedaa; 09-10-2008 at 01:30 PM.

  5. #5
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    How can I reduce the width of the selected item.
    The JList api has setFixedWidth/Height methods you could use to move the list items closer together.
    If you want the selectionColor to cover only the rectangle enclosing the icon and string then you may have to look at some plaf code. You might start with the paintImpl and paintCell methods in the BasicListUI class. You could try calculating the rectangle union of the icon and text rectangles and paint it in the backgroundSelection color.

  6. #6
    Desperado is offline Member
    Join Date
    Dec 2009
    Posts
    8
    Rep Power
    0

    Default

    Hello! Could anybody help me with a function of adding(populating) \ removing items from Jlist?
    I am selecting some files with Swing File chooser, and setting them to Jlist.

    Java Code:
    File[] sf;
    sf = chooser.getSelectedFiles();
    checkBoxList.setListData(sf);
    But I need multiple adding of these files, and for now have no idea how to add more items to list.

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

    Default

    Hey Desperado -- welcome to the forum!

    I think that the answer to your question is to use the right list model, but before we go further, I will ask however that you please create your own question in its own thread rather than hijack an old thread. Then we can discuss this more fully. Thanks for your cooperation!

  8. #8
    Desperado is offline Member
    Join Date
    Dec 2009
    Posts
    8
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Hey Desperado -- welcome to the forum!

    I think that the answer to your question is to use the right list model, but before we go further, I will ask however that you please create your own question in its own thread rather than hijack an old thread. Then we can discuss this more fully. Thanks for your cooperation!
    Thanks, done..

Similar Threads

  1. JList and JPanels
    By JetsYanks in forum New To Java
    Replies: 8
    Last Post: 12-25-2009, 02:11 PM
  2. About JList
    By hungleon88 in forum Advanced Java
    Replies: 5
    Last Post: 08-30-2008, 09:24 PM
  3. JList problem
    By zizou147 in forum Advanced Java
    Replies: 1
    Last Post: 04-17-2008, 08:50 AM
  4. Help with JList
    By Albert in forum NetBeans
    Replies: 1
    Last Post: 07-13-2007, 03:42 PM
  5. add a jlist column
    By Alan in forum JCreator
    Replies: 1
    Last Post: 05-28-2007, 04:51 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
  •