Results 1 to 5 of 5
  1. #1
    kosmos890 is offline Member
    Join Date
    Apr 2012
    Posts
    40
    Rep Power
    0

    Default Problem with JTree selection

    Sorry for my bad english.
    I create a JDialog to show a filesystem using a JTree.

    The class FileTreeModel is my own implementation of TreeModel interface
    I have used code from here

    My MainFrame has a JButton. When the JButton is pressed a JDialog is created.
    The FileSystemPanel is added to the JDialog.

    Each node of this JTree represents a file and I want to get the file's name.
    FileSystemPanel implements TreeSelectionListener.

    The problem is that I have a Null Pointer Exception at valueChangedMethod
    How do I fix this problem?

    If I place FileSystemPanel onto a JFrame the code works.

    Java Code:
    public class MainFrame extends JFrame{
        
        private JButton btn;
        private JDialog dialog;
        private FileSystemPanel fPanel;
        
        public MainFrame(){
            super("MainFrame");
            setSize(300, 100);
            
            Container pane = getContentPane();
            pane.setLayout(new FlowLayout());
            
            btn=new JButton("Show dialog");
            
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    
                    fPanel=new FileSystemPanel();
                    
                    dialog=new JDialog();
                    dialog.setSize(500, 500);
                    dialog.setVisible(true);
                    dialog.setLayout(new BorderLayout());
                    dialog.add(fPanel);
                }
            });
            
            getContentPane().add(btn);        
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }    
        public static void main(String[] args){
            new MainFrame().setVisible(true);
        }
    }
    Java Code:
    public class FileSystemPanel extends JPanel implements TreeSelectionListener {
    
        private File root;
        private JTree tree;
        private JLabel label;
    
        public FileSystemPanel() {
            root = new File(System.getProperty("user.home"));
            FileTreeModel model = new FileTreeModel(root);
            tree = new JTree();
            tree.setModel(model);
            tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
            tree.addTreeSelectionListener(this);
    
            JScrollPane pane = new JScrollPane(tree);
            add(pane);
    
            label = new JLabel("filename : ");
            add(label);
    
            setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
            setVisible(true);
        }
    
        @Override
        public void valueChanged(TreeSelectionEvent e) {
    
    //java.lang.NullPointerException
            Object lastPathComponent = tree.getSelectionPath().getLastPathComponent();
    
            //Instance of inner class TreeFile 
            if (lastPathComponent instanceof File) {
                File file = (File) lastPathComponent;
                label.setText(file.getName());
            }
        }
    }
    Java Code:
    class FileTreeModel implements TreeModel {
    
        protected File root;
    
        public FileTreeModel(File root) {
            this.root = root;
        }
    
        @Override
        public Object getRoot() {
            return root;
        }
    
        @Override
        public boolean isLeaf(Object node) {
            return ((File) node).isFile();
        }
    
        // Tell JTree how many children a node has
        @Override
        public int getChildCount(Object parent) {
    
            File[] children = ((File) parent).listFiles();
    
            if (children == null) {
                return 0;
            }
    
            int counter = 0;
    
            for (File f : children) {
                if (!f.getName().startsWith(".")) {
                    counter++;
                }
            }
            return counter;
        }
    
        @Override
        public Object getChild(Object parent, int index) {
    
            File[] children = ((File) parent).listFiles();
    
            if ((children == null) || (index >= children.length)) {
                return null;
            }
    
            ArrayList<String> dirs = new ArrayList<>();
            ArrayList<String> files = new ArrayList<>();
    
            for (File f : children) {
    
                if (f.getName().startsWith(".")) {
                    continue;
                } else if (f.isDirectory()) {
                    dirs.add(f.getName());
                } else if (f.isFile()) {
                    files.add(f.getName());
                }
            }
    
            Collections.sort(dirs);
            Collections.sort(files);
    
            ArrayList<String> list = new ArrayList<>();
            list.addAll(dirs);
            list.addAll(files);
    
            return new TreeFile((File) parent, (String) (list.toArray())[index]);
        }
    
        @Override
        public int getIndexOfChild(Object parent, Object child) {
            String[] children = ((File) parent).list();
            if (children == null) {
                return -1;
            }
    
            String childname = ((File) child).getName();
    
            for (int i = 0; i < children.length; i++) {
                if (childname.equals(children[i])) {
                    return i;
                }
            }
            return -1;
        }
    
        //Not an editable tree model
        @Override
        public void valueForPathChanged(TreePath path, Object newvalue) {
        }
    
        //Not an editable tree model
        @Override
        public void addTreeModelListener(TreeModelListener l) {
        }
    
        //Not an editable tree model
        @Override
        public void removeTreeModelListener(TreeModelListener l) {
        }
    
        //Use this class to display directory or file name by calling the File.toString() method.
        private class TreeFile extends File {
    
            public TreeFile(File parent, String child) {
                super(parent, child);
            }
    
            @Override
            public String toString() {
                return getName();
            }
        }
    }

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,411
    Rep Power
    5

    Default Re: Problem with JTree selection

    Well, I can't help you since it works just fine for me.

    In your valueChanged method, why not print out tree. And if that is not null, then print out tree.getSelectionPath(), followed by
    tree.getSelectionPath().getLastPathComponent().

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  3. #3
    kosmos890 is offline Member
    Join Date
    Apr 2012
    Posts
    40
    Rep Power
    0

    Default Re: Problem with JTree selection

    @jim829
    Please select and expand some nodes and you will have a NPE

    From JTree code

    Java Code:
        protected void fireValueChanged(TreeSelectionEvent e) {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            // Process the listeners last to first, notifying
            // those that are interested in this event
            for (int i = listeners.length-2; i>=0; i-=2) {
                // TreeSelectionEvent e = null;
                if (listeners[i]==TreeSelectionListener.class) {
                    // Lazily create the event:
                    // if (e == null)
                    // e = new ListSelectionEvent(this, firstIndex, lastIndex);
    //This line throws NPE
                    ((TreeSelectionListener)listeners[i+1]).valueChanged(e);
                }
            }
        }
    My OS is linux 3.2.0-0.bpo.2-686-pae and my java version is 1.7.0_25

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,411
    Rep Power
    5

    Default Re: Problem with JTree selection

    It took me a few minutes to figure out how to repeat the problem. If you try to close a node where one of its children have been selected, the getSelectionPath will return null. This is normal behavior but must be accounted for. If the tree.getSelectionPath() returns null then return null from the valueChanged method.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  5. #5
    kosmos890 is offline Member
    Join Date
    Apr 2012
    Posts
    40
    Rep Power
    0

    Default Re: Problem with JTree selection

    @jim 829

    If you try to close a node where one of its children have been selected, the getSelectionPath will return null.
    This is a very important notice!!!

    Thanks I fix my problem.

    Java Code:
     @Override
        public void valueChanged(TreeSelectionEvent e) {
    
            if (tree.isSelectionEmpty() || tree.getSelectionPath() == null) {
                return;
            }
    
            Object lastPathComponent = tree.getSelectionPath().getLastPathComponent();
    
            File file = (File) lastPathComponent;
            label.setText(file.getName());
        }
    }

Similar Threads

  1. JTree Lazy loading - Node Expand/Selection issue
    By msambasiva in forum AWT / Swing
    Replies: 1
    Last Post: 07-12-2013, 06:35 AM
  2. JTree Programmatic Node Expansion and Selection Probelm
    By hemanthjava in forum AWT / Swing
    Replies: 3
    Last Post: 01-16-2013, 07:23 AM
  3. JTree rendering problem
    By kmm1977 in forum AWT / Swing
    Replies: 5
    Last Post: 07-07-2010, 12:02 PM
  4. JTree Problem
    By ngpamela in forum XML
    Replies: 0
    Last Post: 12-10-2008, 04:10 PM
  5. Node selection in jtree
    By Preethi in forum AWT / Swing
    Replies: 4
    Last Post: 06-19-2008, 11:25 PM

Posting Permissions

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