JList and JTree

Hello,
I have a list of servers in a JList( is a seperate class) and when i am selecting a server name from the JList i am calling this value in my main class and I am trying to use this selected value from the Jlist to create a new JTree node but the value is not being displayed as a node.
Any body having ideas as to why?
Reg,
suri

Hello,
Thanks for ur replies. I have tried the following way but still no results the node is not appearing in the JTree.
Here logon(this is a listBox class and contains a JList with a list of server names)
and root1 is the parent .
DefaultMutableTreeNode new1 = new DefaultMutableTreeNode(logon.getValue(), true);
     int childCnt = root1.getChildCount();
     treeModel.insertNodeInto(new1, root1, childCnt);
treeModel.reload(new1);
treeModel.nodeStructureChanged(new1);
JTree1.revalidate();
JPanel1.revalidate();
Any body any ideas .
Thanks,
reg,
suri

Similar Messages

  • Consume MouseEvent to prevent JList and JTree from receiving?!

    I have a JTree and a JList where I have made the CellRenderer so that it has a "button" area. When this button is clicked, I want something to happen. This I have achieved just nicely with a MouseListener, as per suggestion from JavaDocs.
    However, the problem is that when a click is deemed to be within the "button", I do not want the tree or list to process it anymore. But doing e.consume(), both on mousePressed or mouseClicked (though it obviously is pressed the JList and JTree themselves listen to) doesn't do jack.
    How can I achieve this functionality?

    da.futt wrote:
    stolsvik wrote:
    Okay, I managed with a hack: It is the order of listeners that's the problem: The ListUI's MouseListener is installed before mine, and hence will get the MouseEvent before me, so it has already processed it when I get it, and hence consuming it makes no difference. No. Normally, listeners are notified latest-registered to earliest-registered. I don't remember seeing an exception to that rule in the core API. well, you are both right (or wrong ;-) - the rule is: the order of listener notification is undefined, it's an implementation detail which listeners must not rely on. "Anecdotical" experience is that AWTListeners are notified first-registered-first-served, while listeners to swing specific events are notified last-registered-first-served. Below is a snippet (formulated in context of SwingX convenience classes, too lazy ...) showing that difference.
    The latter probably stems from hefty c&p of notification by walking the EventListenerList: the earliest code was implemented very near the beginning of Swing when every little drop of assumed performance optimization was squeezed, such as walking from back to front. Using EventListenerList involves lots of code duplication ... so lazy devs as we all are, simply c&p'ed that loop and just changed the concrete event type and method name. More recently, as in the we-use-all-those-nifty-cool-language-features ;-) I've seen more usage of forEach loops (f.i. in beansbinding) so notification is back to first-in-first-served :-)
    Bottom line: don't rely on any sequence - if needed, use an eventBus (or proxy or however it's called) and define the order there. Darryl's suggestion is as close as we can get in Swing (as it's not supported) but not entirely safe: there's no way to get notified when listeners are added/removed and no hook where to plug-in such a bus into the ui-delegate where it would belong.
    Cheers
    Jeanette
    // output
    02.10.2009 14:21:57 org.jdesktop.swingx.event.EventOrderCheck$1 mousePressed
    INFO: first added mouseListener
    02.10.2009 14:21:57 org.jdesktop.swingx.event.EventOrderCheck$2 mousePressed
    INFO: second added mouseListener
    02.10.2009 14:21:58 org.jdesktop.swingx.event.EventOrderCheck$4 valueChanged
    INFO: second added listSelectionListener
    02.10.2009 14:21:58 org.jdesktop.swingx.event.EventOrderCheck$3 valueChanged
    INFO: first added listSelectionListener
    // produced by
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.util.logging.Logger;
    import javax.swing.JList;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import org.jdesktop.swingx.InteractiveTestCase;
    import org.jdesktop.test.AncientSwingTeam;
    public class EventOrderCheck extends InteractiveTestCase {
        public void interactiveOrderAWTEvent() {
            JList list = new JList(AncientSwingTeam.createNamedColorListModel());
            MouseListener first = new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    LOG.info("first added mouseListener");
            MouseListener second = new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    LOG.info("second added mouseListener");
            list.addMouseListener(first);
            list.addMouseListener(second);
            ListSelectionListener firstSelection = new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (e.getValueIsAdjusting()) return;
                    LOG.info("first added listSelectionListener");
            ListSelectionListener secondSelection = new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (e.getValueIsAdjusting()) return;
                    LOG.info("second added listSelectionListener");
            list.addListSelectionListener(firstSelection);
            list.addListSelectionListener(secondSelection);
            showWithScrollingInFrame(list, "event order");
        @SuppressWarnings("unused")
        private static final Logger LOG = Logger.getLogger(EventOrderCheck.class
                .getName());
        public static void main(String[] args) {
            EventOrderCheck test = new EventOrderCheck();
            try {
                test.runInteractiveTests();
            } catch (Exception e) {
                e.printStackTrace();
    }

  • JTree, JList and file selection

    I have a file selection JPanel that I'm creating that has a JTree on the left representing folders and a JList on the right that should have the files and folders listed to be able to select. I have two problems at this point. First, and more important, when a folder is selected, the JList doesn't update to the files in the new folder and I don't see what's keeping it from working. Second, when clicking on a folder in the JTree, it drops the folder to the end of the list and then lets you expand it to the other folders, also it shows the whole folder path instead of just the folder name.
    This is still my first venture into JTrees and JLists and I'm still really new at JPanel and anything GUI, so my code may not make the most sense, but right now I'm just trying to get it to work.
    Thank you.
    public class FileSelection extends JFrame{
              Container gcp = getContentPane();
              File dir=new File("c:/");
              private JList fileList;
              JTree tree;
              DefaultMutableTreeNode folders;
              String filePath,selectedFile="", path;
              TreePath selPath;
              FileListPanel fileLP;
              FolderListPanel folderLP;
              JScrollPane listScroller;
              public FileSelection(String name){
                   super(name);
                   gcp.setLayout(new BorderLayout());
                   fileLP = new FileListPanel();
                   folderLP = new FolderListPanel();
                   gcp.add(fileLP, BorderLayout.CENTER);
                   gcp.add(folderLP, BorderLayout.WEST);
                   setVisible(true);
              private class FileListPanel extends JPanel implements ActionListener{
                   public FileListPanel(){
                        final JButton selectItem = new JButton("Select");
                        final JButton cancel = new JButton("Cancel");
                        final JButton changeDir = new JButton("Change Directory");
                        //add buttons
                        add(selectItem);
                        add(changeDir);
                        add(cancel);
                        //instantiate buttons
                        selectItem.setActionCommand("SelectItem");
                        selectItem.addActionListener(this);
                        changeDir.setActionCommand("ChangeDirectory");
                        changeDir.addActionListener(this);
                        cancel.setActionCommand("Cancel");
                        cancel.addActionListener(this);
                        final String[] fileArr=dir.list();
                        fileList = new JList(fileArr);
                        fileList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
                        fileList.setLayoutOrientation(JList.VERTICAL_WRAP);
                        fileList.setVisible(true);
                        fileList.setVisibleRowCount(-1);
                        fileList.setSelectedIndex(0);
                        listScroller = new JScrollPane(fileList);
                        listScroller.setPreferredSize(new Dimension(200,200));
                        listScroller.setAlignmentX(LEFT_ALIGNMENT);
                        add(listScroller);
                        MouseListener mouseListener = new MouseAdapter(){
                             public void mouseClicked(MouseEvent e){
                                  if(e.getClickCount()==2){
                                       int itemIndex = fileList.locationToIndex(e.getPoint());
                                       currFile=fileArr[itemIndex];
                                       dispose();
                        fileList.addMouseListener(mouseListener);
                   public void actionPerformed(ActionEvent e){
                        if("SelectItem".equals(e.getActionCommand())){
                             currFile=(String)fileList.getSelectedValue();
                             dispose();
                        }else{
                        if("Cancel".equals(e.getActionCommand())){
                             dispose();
                        }else{
                        if("ChangeDirectory".equals(e.getActionCommand())){
                             ChangeDir cd = new ChangeDir("Select Directory");
                             cd.setSize(new Dimension(300,275));
                             cd.setLocation(500, 225);
              private class FolderListPanel extends JPanel{
                   public FolderListPanel(){
                        String[] files = dir.list();
                        DefaultMutableTreeNode topNode = new DefaultMutableTreeNode("Files");
                        folders = new DefaultMutableTreeNode("C:/");
                        topNode.add(folders);
                        folders = getFolders(dir, folders);
                        tree = new JTree(topNode);
                        tree.setVisible(true);
                        JScrollPane treeScroller = new JScrollPane(tree);
                        treeScroller.setPreferredSize(new Dimension(500,233));
                        treeScroller.setAlignmentX(LEFT_ALIGNMENT);
                        add(treeScroller);
                        MouseListener mouseListener = new MouseAdapter(){
                             public void mouseClicked(MouseEvent e){
                                  try{
                                       if(e.getClickCount()==1){
                                            selPath = tree.getPathForLocation(e.getX(), e.getY());
                                            path=selPath.getLastPathComponent().toString();
                                            dir = new File(path);
                                            TreeNode tn=findNode(folders, path);                    
                                            if(tn!=null){
                                                 folders.add((MutableTreeNode) getTreeNode(dir, (DefaultMutableTreeNode) tn));
                                            tree.updateUI();
                                            final String[] fileArr=dir.list();
                                            fileList = new JList(fileArr);
                                            fileList.updateUI();
                                            listScroller.updateUI();
                                            fileLP = new FileListPanel();
                                  }catch(NullPointerException npe){
                        tree.addMouseListener(mouseListener);
                   public DefaultMutableTreeNode getFolders(File dir, DefaultMutableTreeNode folders){
                        File[] folderList = dir.listFiles();
                        int check=0;
                        for(int x=0;x<folderList.length;x++){
                             if(folderList[x].isDirectory()){
                                  folders.add(new DefaultMutableTreeNode(folderList[x]));               
                        return folders;
                   public TreeNode getTreeNode(File dir, DefaultMutableTreeNode folders){
                        File[] folderList = dir.listFiles();
                        int check=0;
                        for(int x=0;x<folderList.length;x++){
                             if(folderList[x].isDirectory()){
                                  folders.add(new DefaultMutableTreeNode(folderList[x]));               
                        return folders;
                   public TreeNode findNode(DefaultMutableTreeNode folders, String node){
                        Enumeration children = folders.postorderEnumeration();
                        Object current;
                        while(children.hasMoreElements()){
                             current = children.nextElement();
                             if(current.toString().equals(node)){
                                  return (TreeNode)current;
                        return null;
         }

    Wow! I changed the FolderListPanel's mouseListener to:
    tree.addTreeSelectionListener(new TreeSelectionListener(){
                             public void valueChanged(TreeSelectionEvent tse){
                                  DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
                                  if(node==null)return;
                                  Object nodeInfo = node.getUserObject();
                                  dir=new File(nodeInfo.toString());
                                  folders.add((MutableTreeNode) getFolders(dir,node));
                        });and it's amazing how much better the tree is!!! But I still don't have the JList part working. I changed the JList and the FileListPanel to public from private, but that didn't change anything.

  • Interesting Focus II: JComboBox, 2 JLists and 1 Button

    Hi All,
    Another Interesting Keyboard Focus Question:
    What we want to do?
    Let's say we want to build a JComboBox whose popup contains 2 JLists and a button.
    What we would probably want to do is:
    comboBox.setUI(new MyComboBoxUI());
    MyComboBoxUI will extend BasicComboBoxUI and
    ovveride createPopup to return a BasicComboPopup subclass
    which will add the other JList and JButton.
    (One can argue that this is not a JComboBox anymore, but bare with me)
    Does it work?
    This will work great with the Mouse, but with the Keyboard we face a problem:
    After our popup is displayed, The JComboBox Still Has The Focus - Any UP or DOWN Events are really proccessed by the JComboBox which simulates JList navigation...
    This is happening because the popup is not keyboard-focusable (and so do all of its components)
    Where' s the problem?
    We want to be able to:
    1. Press TAB to navigate thru the 3 components
    2. Press UP and DOWN to navigate the two JLists
    3. Press Space to activate the JButton
    Possible solutions:
    1.
    Don't subclass BasicComboPopup and write a ComboPopup which uses a Focusable JWindow.
    Problem: The JComboBox will lose the focus when the popup opens
    2.
    Simulate all the DOWN/UP/TAB/SPACE events to the popup
    Problem: The components are not focusable, hence there is no indication
    of who is the current focused component
    (Might be solved by surrounding the 'focused' component with a border)
    Your thoughts?
    If you haven't fell asleep by now, you are welcomed to share you ideas, Thanks
    Eyal Katz

    Sorry, I don't understand what you are trying to accomplish. However one line did catch my eye.
    This is happening because the popup is not keyboard-focusable The code in the popupPopup() method in the following post might help:
    http://forum.java.sun.com/thread.jspa?threadID=636842

  • JList and ListModel, can anyone explain the basics?

    Hi
    I have an object A containing a Vector X of objects. I want to display them in a JList. I could always use DefaultListModel and copy the items of the Vector X into the default list model using addElement. But that would create a copy of the information in vector X. That is exactly why one should use a custom list model to ensure that the data is in sync with the GUI .
    I want to add and remove items from the JList, and simultaious add and remove items from the Vector X. Can anyone proviede a samll example of how to do this.
    I have tryed myselfe, but I can not get the JList updated with the changes of the listmodel. I have read the documentation about ListDataListener, but I just don't get it. A small example would realy be appreciated!
    // Mattias

    Yse I have read the tutorial. But I don't understand it.
    Here is a small example program. Can anyone change the code so the list is updated with the canges that obviously take place (as one can see by pressing the "Dump button")
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    class ListTest extends JFrame implements ActionListener , ListDataListener {
        JList list;
        MyListModel myListModel;
        MyDataObject myDataObject;
        ListTest() {
            JPanel p = new JPanel();
            myDataObject = new MyDataObject();
            myListModel = new MyListModel(myDataObject.x);
            list = new JList(myListModel);
            myListModel.addListDataListener(this);
            JScrollPane listScrollPane = new JScrollPane(list);
            listScrollPane.setPreferredSize(new Dimension(200, 100));
            p.add(listScrollPane);
            JButton b1 = new JButton("Add");
            b1.addActionListener(this);
            p.add(b1);
            JButton b2 = new JButton("Remove");
            b2.addActionListener(this);
            p.add(b2);
            JButton b3 = new JButton("Dump");
            b3.addActionListener(this);
            p.add(b3);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            getContentPane().add(p);
            pack();
            show();
        public void actionPerformed(ActionEvent e) {
            if (e.getActionCommand().equals("Add")) {
                myListModel.addElement(""+ (1+myListModel.getSize()) );
                System.out.println("Added a row to the list");
            if (e.getActionCommand().equals("Remove")) {
                if (myListModel.getSize()>0) {
                    myListModel.remove(myListModel.getSize()-1);
                    System.out.println("Removed last element from the list");
                else {
                    System.out.println("No more elements to remove");
            if (e.getActionCommand().equals("Dump")) {
                System.out.println("\n\nData in the list model:");
                for (int i=0; i<myListModel.getSize() ; i++) {
                    System.out.println(myListModel.getElementAt(i));
                System.out.println("That should be the same as the vector x in the object myDataObject  :");
                for (int i=0; i<myListModel.getSize() ; i++) {
                    System.out.println(myDataObject.x.get(i));
        public void contentsChanged(ListDataEvent e) {
            System.out.println("contentsChanged");
        public void intervalAdded(ListDataEvent e) {
            System.out.println("intervalAdded");
        public void intervalRemoved(ListDataEvent e) {
            System.out.println("intervalRemoved");
        public static void main(String args[]) {
            new ListTest();
    class MyDataObject {
        Vector x;
        MyDataObject() {
            x=new Vector();
            x.addElement("1");
            x.addElement("2");
    class MyListModel extends AbstractListModel {
        Vector v;
        MyListModel(Vector v) {
            this.v=v;
        public void addElement(Object o) {
            v.addElement(o);
        public Object remove(int index) {
            return v.remove(index);
        public Object getElementAt(int index) {
            return v.get(index);
        public int getSize() {
            return v.size();
    </pre>

  • Key pressed in Jlist and selecting the item of key list accordingly

    Hi,
    I have a JList with the items in sorted order.Now I want that if a person presses any key (say K) then the first item starting with K should be selected.Hmmm I can do it by addding a key listener to the list and cheking all the items in the list ,by traversing through the whole lenght of JList and selecting the item if it starts with the character of the key pressed.
    But i was thinking if there is any better way to do that?
    Regards Amin

    see bugid: 4654916 - it does say that the the
    scrolling for the JList should now work with keyboard
    selection.I have the same problem. Thanx for the hint with the bugid. Saw a good workaround there with a simple subclass of JList. Works for me although it is annoying to subclass JList all the time. The bug seems not to be fixed in the 1.4.1 JDK.
    Andreas

  • Problems JList and DefaultListModel

    Hi!
    I've got a problem with the removing of items from a DefaultListModel.
    Assume this:
    public class ImageList extends JList implements DropTargetListener {
    private DefaultListModel dlm = new DefaultListModel();
    public void setListData(ArrayList al) {
    for(...) {
    //do some stuff here
    dlm.addElement(al.get(i));
    this.setModel(dlm);
    }In the main Frameclass are an instance of ImageList and a JButton for deleting a selected item from the list.
    content of the actionPerfomed-method of JButton:
    DefaultListModel model = (DefaultListModel)customContentPane.imageList.getModel();
    int index = customContentPane.imageList.getSelectedIndex();
    if(index!=-1) {
    imageData.remove(index);
    model.remove(index);
    }I'm developing with JBuilder and JDK 1.3.0_02 and there the removing works fine!
    But with JDK 1.4.1-rc-b19 i'm getting an ArrayIndexOutOfBoundsException when i try to delete the last item. The exceptions says index: 0, size: 0!
    But same code works without any problem with 1.3!!
    Does anybody knows a solution?
    Thanks in advance
    Martin

    Its me again!
    After some debugging i found out, the IndexOutOfBoundsException always gives 'Index: -1' back, although an item IS selected!
    And the imageList.getSelectedIndex() returns the true current selected item and not -1.
    Is it a bug in the JList and the DefaultListModel?

  • DnD between Jlist and Canvas...

    Is it all possible to drag the list item from JList and drop it inside the Canvas and place a reference (e.g. lsit item name ) at the exact coordinates where the drop is performed?
    Additionally, for the purpose of my project the Canvas already contains an image of a model space and would need to stay in the background all along!
    Please if anyone have any thoughts, recomendations, suggestions post these here.
    Thanks

    Please, is drag and drop possible between JList and Canvas components so that the inserted item from JList is displayed over the image displayed in the Canvas component?

  • Regarding_Height in JSplitPane in which JList And JTextArea

    Hi All,
    I have JSplitPane in which two components Jlist and JTextArea
    placed . Here when I type the text in JTextArea respective row no
    is appeared in JList.Here my problem is how to set the row hieght
    of both JTextArea and JList to equal size ....
    Can any body have the idea pls help me.
    Thanks in advance

    have you experimented with JTextArea's getRowHeight() and
    JLists's get/setFixedCellHeight()?

  • DnD from JList into JTree

    Can anyone point me at a tutorial demonstarting how to drag objects from a JList into a JTree?
    many thanks

    Let me add some more information to maybe get some suggestions:
    I have DnD implemented in my tree - as my nodes are DefaultMutableTreeNode it is easy to getUserObject() and carry out the necessary changes to model and underlying object.
    In my JList(x2) I have custom objects, DnD is implemented on each list. My question is how should I wrap my JList objects so that I can retrieve the user object when I drop it into my tree?
    I have found an example of dragging nodes from one tree to another tree, but this is of little help as the DnD is simply dragging the String object about.
    Any pointers/suggestions please

  • Populate Jlist from Jtree

    hi !!!!
    In my project I have added a Jtree and a Jlist
    I have been trying to populate a Jlist with the item that is selected in the Jtree...so I added a treeSelection listener .I am Able to display the selected item but able to add only one item to my Jlist.....
    pls help me
    public void valueChanged(TreeSelectionEvent e) {
           DefaultMutableTreeNode node = (DefaultMutableTreeNode)jTree1.getLastSelectedPathComponent();
            if (node == null) return;
            System.out.println(node.getUserObject().toString());
            String[] list = {(String) node.getUserObject()};
            System.out.println(list);
            Object[] listOb=(Object[])list;
            listRole.setListData((Object[]) listOb);
          // listRole.setListData( (Vector<?>) node.getUserObject() );
        }    }output
    ENTER BACKLOG ENTRY
    [Ljava.lang.String;@b1c260
    PRINT
    [Ljava.lang.String;@1dd46f7
    ADD SCHOOL DATA
    [Ljava.lang.String;@1b26af3
    UPDATE SCHOOL DATA
    [Ljava.lang.String;@eb017e
    Edited by: rashi13 on Mar 10, 2008 6:57 AM

    hi all
    the Jlist is populating now after I used default list model
    now i have a new problem...I thought of removing elements from
    the list when user clicks on it
    my code for that is
    public void valueChanged(ListSelectionEvent e) {
    //        if (e.getValueIsAdjusting() == false) {
            int index=(int)listRole.getSelectedIndex();
            System.out.println(index);
            listModel.removeElementAt(index);
            if (index == listModel.getSize())//removed item in last position
                index--;
            listRole.setSelectedIndex(index);   //otherwise select same index
        }but whenever i click on any item
    it is giving array out of bound exception
    and item is removed but the next element is duplicated
    why is this happening ?
    please help me

  • Problem with JPopupMenu and JTree

    Hi,
    Is there any way to have different JPopupMenu for every node.
    When I right click on the treenode there is popup menu have a "*JCheckBoxMenuItem*". By default the value of that checkbox is false. Now when i try to right click on a particular node and select the checkbox the selected value gets applied to rest of all nodes also.
    How can i just set the value of the checkbox to one perticular node.
    my code is
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreePopupMenuTest {
      public JComponent makeUI() {
        JTree tree = new JTree();
        tree.setComponentPopupMenu(new TreePopupMenu());
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(tree));
        p.setPreferredSize(new Dimension(320, 240));
        return p;
      class TreePopupMenu extends JPopupMenu {
        private TreePath path;
        private JCheckBoxMenuItem compress=new JCheckBoxMenuItem("Compress");
        public TreePopupMenu() {
          super();
          add(compress);
          compress.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ie) {
                            if(compress.getState()){
                                 compress.setState(true);
                                    System.out.println("compress clicked");
                            else{
                                 compress.setState(false);
                                    System.out.println("uncompress");
        public void show(Component c, int x, int y) {
          JTree tree = (JTree)c;
          path = tree.getPathForLocation(x, y);
          if(path!=null && path==tree.getAnchorSelectionPath()) {
            super.show(c, x, y);
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TreePopupMenuTest().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }Please help me as soon as possible.
    Thanks.
    Edited by: Kavita_S on Apr 23, 2009 11:49 PM

    Hi,
    Do you know this link?
    [How to Use Trees|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html]
    Please help me as soon as possible.Sorry that I'm not good at English, I don't understand what you mean.
    Anyway, here's a quick example:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreePopupMenuTest3 {
      public JComponent makeUI() {
        JTree tree = new JTree();
        tree.setComponentPopupMenu(new TreePopupMenu());
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(tree));
        p.setPreferredSize(new Dimension(320, 240));
        return p;
      class TreePopupMenu extends JPopupMenu {
        private TreePath path;
        private JCheckBoxMenuItem compress = new JCheckBoxMenuItem("Compress");
        public TreePopupMenu() {
          super();
          add(compress);
          compress.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ie) {
              if (compress.getState()) {
                System.out.println("compress clicked");
                setSelectedPath(path, true);
              } else {
                System.out.println("uncompress");
                setSelectedPath(path, false);
        public void show(Component c, int x, int y) {
          JTree tree = (JTree)c;
          path = tree.getPathForLocation(x, y);
          if (path!=null && path==tree.getAnchorSelectionPath()) {
            compress.setState(isSelectedPath(path));
            super.show(c, x, y);
      class MyData {
        public boolean flag;
        public String name;
        public MyData(String name, boolean flag) {
          this.name = name;
          this.flag = flag;
        @Override public String toString() {
          return name;
      //private Set<TreePath> selectedPath = new HashSet<TreePath>();
      private void setSelectedPath(TreePath p, boolean flag) {
        //if (flag) selectedPath.add(p);
        //else    selectedPath.remove(p);
        DefaultMutableTreeNode node =
              (DefaultMutableTreeNode)p.getLastPathComponent();
        Object o = node.getUserObject();
        if (o instanceof MyData) {
          ((MyData)o).flag = flag;
        } else {
          node.setUserObject(new MyData(o.toString(), flag));
      private boolean isSelectedPath(TreePath p) {
        //return selectedPath.contains(p);
        Object o =
              ((DefaultMutableTreeNode)p.getLastPathComponent()).getUserObject();
        return (o instanceof MyData)?((MyData)o).flag:false;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TreePopupMenuTest3().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

  • JSplitPane, JScrollPane and JTree resizing

    Hi,
    In a JSplitPane, I have, in the left part, a JScrollPane, containing a JTree and, in the right part, I have an other panel.
    When I click on different nodes in the JTree, the width of the left part changes, so the JSplitPane separator moves. How to avoid that ? I would prefer a scrolling move inside the JScrollPane !
    I am using JDK 1.3
    Thanks
    Olivier Scalbert

    Try to define the JScrollPane as
    public JScrollPane(Component view, int vsbPolicy, int hsbPolicy)
    Use vsbPolicy and hsbPolicy like the VERTICAL_SCROLLBAR_AS_NEEDED
    HORIZONTAL_SCROLLBAR_AS_NEEDED respectively.
    Then define the setPreferredSize to your JScrollPane. This preferredSize must be smaller than the size of the Component view if you want to see the ScrollBar.
    By the way, when you define your JSplitPane have to define the setOneTouchExpandable(true);?

  • Vector and Jtree 4Duke

    hi
    i am having poblem with my jtree as i am not able to show the object in my vector as a different node
    {each object is node of my tree}
    unfortunately they all appear flat in the root, and in sequence{as one node} ??
    i have done everything but still no answer??
    thanks in advance for any solution
    public class Gui extends JFrame
    {  Vector root = new Vector();
    public JTree theTree ;
    public SERGui( )
    System.out.println(root.size());//root vector is empty
    roott = new DefaultMutableTreeNode (root);
    model = new DefaultTreeModel (roott) ;
    theTree = new JTree (model);      
    public Vector addOne(String newString)
    if (!root.contains(getQuery))
               root.add(newString);
    model.reload();
    // //updateTree(); i also try this method whiich does not work
    return root;
    public void updateTree(){
    DefaultMutableTreeNode v = (DefaultMutableTreeNode)theTree.getModel().getRoot();
    for(int i=0;i<root.size();i++)
                   DefaultMutableTreeNode node = (DefaultMutableTreeNode)root.elementAt(i);
                   roott.add(node);
    ((DefaultTreeModel)theTree.getModel()).reload(v);
    //DefaultMutableTreeNode node = null;
    print_vector(root);
      //root.clear();
         }and my other class
    where i call this methos is as follow
    Class Search()
    public void countWord(String newString)
    {Gui.addOne(newString);
    }}

    You are passing a Vector into the constructor of the DefaultMutableTreeNode to create the root of your tree. The DefaultMutableTreeNode will use this object's string representation (by calling toString on whatever object you pass in its constructor) as the name of the tree node. So basically you will see the entire contents of the vector as the name of your root node.
    You need to traverse your vector, and use each element to create a DefaultMutableTreeNode and add it to your root node.
    here is the modified code
    public class Gui extends JFrame {
    private Vector rootVector = new Vector();
    private JTree theTree;
    private DefaultMutableTreeNode rootNode;
    private DefaultTreeModel model;
    public Gui() {
    System.out.println(rootVector.size());
    //root vector is empty
    rootNode = new DefaultMutableTreeNode("Root");
    model = new DefaultTreeModel(rootNode);
    theTree = new JTree(model);
    public Vector addOne(String newString) {
    if (!rootVector.contains(newString)) {
    rootVector.add(newString);
    updateTree();
    return rootVector;
    public void updateTree() {
    rootNode.removeAllChildren();
    for (int i = 0; i < rootVector.size(); i++) {
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(
    rootVector.elementAt(i));
    rootNode.add(node);
    ((DefaultTreeModel) theTree.getModel()).reload(rootNode);
    Hemant Mahidhara

  • JSplitPane and Jtree

    Hi all,
    in my window I've got a JSplitPane with the left component that is a JScrollPane with a Jtree (used as a menu), while in the right side a customized JPanel that changes depending on the selection in the tree on the left.
    My panels are initially created as follows:
         this.splitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
         this.splitter.setOneTouchExpandable(true);
    JScrollPane leftPanel = new JScrollPane( this.menuTree );
              leftPanel.setMinimumSize( new Dimension(300,300) );     
              leftPanel.setMaximumSize(leftPanel.getMinimumSize());
              // add the leftt and right panels
              this.splitter.setLeftComponent( leftPanel );
              this.imagePanel = new ImagePanel(ComponentBuilder.getLogoPath());
              this.rightPanel = this.imagePanel;
              this.splitter.setRightComponent(this.rightPanel);
              // add the splitter to myself
              this.add(new JScrollPane(this.splitter));where the imagepanel is a working panel that shows the project logo. Now what happens is that:
    1) the logo is cutted to a size I don't know how is calculated, since the image panel is working fine (if I place on a separate window I can see the image right)
    2) most important when a user selects something in the tree on the left panel, so the right panel changes, the left panel is moved around the window depending on the size of the right panel.
    Is it possible to fix the left panel not only as size, but also in the position of the window, thus the remaining part of the window will be occupied by the right panel without moving the left one? In my frame I'm using a BorderLayout, and the panel containing the splitpane is set at the center (no components on the right and on the left).
    Thanks,
    Luca

    Thanks for your reply, but the only thing I noticed is that the code you're showing works a little more with sizes, that is something I've already tried. By the way, the following is a running example that loads a tree/menu and the logo.png image.
    Any idea about its behaviour?
    Thanks,
    Luca
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.awt.image.*;
    class ImagePanel extends JPanel implements ImageObserver
         * The image to display
        protected Image image=null;
         * This flag indicates if the image is complete or not.
        protected boolean isComplete=false;
         * The dimension of the panel.
        protected int width=0,height=0;
         * This is the message to display during loading.
        protected String message="Loading...";
         * Default constructor.
         * @param image the image object.
        public ImagePanel(Image image)
              super();
              this.image=image;
         * Overloaded constructor. It try to load the image itself. You should use
         * this to avoid image flicking problems. This method use all the
         * capabilities of the ImageObserver.
         * @param image the image file name
        public ImagePanel(String image) {
              super();
              /* now load the image */
              Toolkit tk=Toolkit.getDefaultToolkit();
              this.image=tk.getImage(image);
              /* use the media tracker to wait untill the image is not loaded */
              try{
                  MediaTracker tracker=new MediaTracker(this);
                  tracker.addImage(this.image,0);
                  tracker.waitForID(0);
                  this.isComplete=true;
                  /* now that the image is fully loaded I need to resize the panel to
                  the size of the image */
                  this.width=this.image.getWidth(this);
                  this.height=this.image.getHeight(this);
                  this.setSize(width,height);
                  this.setMinimumSize(getSize());
                  this.setMaximumSize(getSize());
                  this.setVisible(true);
              catch(InterruptedException e){
                  this.message="Exception during loading process!";
                  this.isComplete=false;
         * Draw the image.
        public void paint(Graphics device)   {
              super.paint(device);
              if(this.isComplete==true)     {
                  device.drawImage(this.image,0,0,this.width,this.height,this);
              else     {
                  device.setColor(Color.RED);
                  device.drawString(this.message,20,20);
         * The update image method. This method is called for every update and or
         * error.
        public boolean imageUpdate(Image image,int infoFlags, int x, int y,
                        int width, int height)
              if((infoFlags & ALLBITS)==0)
                  /* the image is complete */
                  this.isComplete=true;
                  repaint();
                  this.setVisible(true);
                  return false;
              else
              if((infoFlags & ERROR)==0 || (infoFlags & ABORT)==0 )
                  /* error or abort */
                  this.isComplete=false;
                  this.message="Error during load process (or abort)";
                  this.repaint();
                  return true;
              else
              if((infoFlags & SOMEBITS)==0)
                  /* some other data loaded, show the loading process percent */
                  int originalWidth=this.image.getWidth(this);
                  int originalHeight=this.image.getHeight(this);
                  int currentWidth=image.getWidth(this);
                  int currentHeight=image.getHeight(this);
                  /* now calculate the total of pixels */
                  long originalTotal=originalWidth*originalHeight;
                  long currentTotal=currentWidth*currentHeight;
                  /* now calculate the percent */
                  float percent=(float)currentTotal/(float)originalTotal *100;
                  /* set the string */
                  this.message="Loading progress: "+(int)percent+" % done";
                  this.repaint();
                  return true;
              return true;
    public class MainPanel extends JPanel {
          * The split pane used for this panel.
         protected JSplitPane splitter = null;
          * The menu tree of this panel.
         protected JTree menuTree = null;
          * The parentFrame frame of this panel
         protected JFrame parentFrame = null;
          * The panel on the right of the window.
         protected JComponent rightPanel = null;
          * The menuTreeRoot node of the menu.
         protected DefaultMutableTreeNode menuTreeRoot = null;
          * The action menu of the JFrame that contains this panel. Such menu is changed depending on the panel
          * shown on the right panel.
         protected JMenu actionMenu = null;
          * The image panel with the image of the logo.
         protected ImagePanel imagePanel = null;
         public final String ROOT_STRING = "Gestione delle risorse umane";
         public final String LEVEL1A_STRING = "Parametrizzazione";
         public final String LEVEL2AA_STRING = "Competenze & Famiglie di competenze";
         public final String LEVEL2AB_STRING = "Gestione dei ruoli";
         public final String LEVEL2AC_STRING = "Associazione ruolo-competenza";
         public final String LEVEL1B_STRING   = "Varie";
         public final String LEVEL2BB_STRING = "Province";
         public final String LEVEL2BC_STRING = "Citta'";
         public final String LEVEL2BD_STRING = "Livelli di istruzione";
         public final String LEVEL2BE_STRING = "Livelli di competenza";
         public final String LEVEL3A_STRING   = "Personale";
         public final String LEVEL3AA_STRING = "Anagrafica di base";
         public final String LEVEL3AB_STRING  = "Ruoli, Competenze e Gradi di Istruzione";
         public final String LEVEL3AC_STRING  = "Storia delle valutazioni delle competenze";
         public final String LEVEL3AD_STRING  = "Valutazione";
          * Default constructor.
          * @param parentFrame the jframe that contains this panel
         public MainPanel(JFrame parent, JMenu actionMenu){
              super();
              this.parentFrame = parent;
              this.initGUI();
              this.actionMenu = actionMenu;
          * Shows the components on the main panel.
         public synchronized void initGUI(){
              // create the split pane
              this.splitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
              this.splitter.setOneTouchExpandable(true);
              //this.splitter.setResizeWeight(0);                    // the right panel gets all the extra space
              // create the left panel with the tree
              DefaultMutableTreeNode root = new DefaultMutableTreeNode(ROOT_STRING);
                   DefaultMutableTreeNode level1a = new DefaultMutableTreeNode(LEVEL1A_STRING);
                        ContainerTreeNode level2aa = new ContainerTreeNode(LEVEL2AA_STRING);     // skills and families
                   DefaultMutableTreeNode level2ab = new DefaultMutableTreeNode(LEVEL2AB_STRING);
                        DefaultMutableTreeNode level2ac = new DefaultMutableTreeNode(LEVEL2AC_STRING);
                   DefaultMutableTreeNode level1b = new DefaultMutableTreeNode(LEVEL1B_STRING);
                        DefaultMutableTreeNode level2bb = new DefaultMutableTreeNode(LEVEL2BB_STRING);
                        DefaultMutableTreeNode level2bc = new DefaultMutableTreeNode(LEVEL2BC_STRING);
                        DefaultMutableTreeNode level2bd = new DefaultMutableTreeNode(LEVEL2BD_STRING);
                        DefaultMutableTreeNode level2be = new DefaultMutableTreeNode(LEVEL2BE_STRING);
                   DefaultMutableTreeNode level3a = new DefaultMutableTreeNode(LEVEL3A_STRING);
                        DefaultMutableTreeNode level3aa = new DefaultMutableTreeNode(LEVEL3AA_STRING);
                        DefaultMutableTreeNode level3ab = new DefaultMutableTreeNode(LEVEL3AB_STRING);
                        DefaultMutableTreeNode level3ac = new DefaultMutableTreeNode(LEVEL3AC_STRING);
                        DefaultMutableTreeNode level3ad = new DefaultMutableTreeNode(LEVEL3AD_STRING);
              // create the tree
              this.menuTreeRoot = root;
              level2ab.add(level2ac);
              level1a.add(level2aa);
              level1b.add(level2bc);
              level1b.add(level2bb);
              level1b.add(level2bd);
              level1b.add(level2be);
              level3a.add(level3aa);
              level3a.add(level3ab);
              level3a.add(level3ac);
              level3a.add(level3ad);
              root.add(level3a);
              root.add(level2ab);
              root.add(level1a);
              root.add(level1b);
              this.menuTree = new JTree(root);
              this.menuTree.setSize(200,200);
              JScrollPane leftPanel = new JScrollPane( this.menuTree );
              leftPanel.setMinimumSize( new Dimension(300,300) );     // it does not affects the dimension, but avoid to resize the left panel
              leftPanel.setMaximumSize(leftPanel.getMinimumSize());
              // add the leftt and right panels
              this.splitter.setLeftComponent( leftPanel );
              this.imagePanel = new ImagePanel("logo.png");
              this.rightPanel = this.imagePanel;
              this.rightPanel.setSize(400,400);
              this.splitter.setRightComponent(this.rightPanel);
              // add the splitter to myself
              this.add(new JScrollPane(this.splitter));
         public static void main(String argv[]){
             JFrame f = new JFrame();
             f.setSize(400,400);
             f.add(new MainPanel(f,null));
             f.setVisible(true);
    }

Maybe you are looking for

  • After IOS 8 upgrade IPad 2 don't start

    Hi, After IOS 8 upgrade my IPad 2 don't start and just show this screen and nothing works.

  • Character set error during startup

    Hi all This is a follow up of the following problem: Paralel Install of Ora8i and Ora9i Please read it before continue. This seems to be a database problem, so that I post it here: I'm going forward with my problem. It seems that's a problem with ver

  • Trying to install a setup on a 64 bit machine with Windows server 2012 R2 which writes to registry FAILES

    My msi is a 32 bit setup. When I install it on a 32 bit machine with Windows XP it works fine . I tried to install it on a 64 bit machine with windows server 2008 and it succeeds While running my setup on a 64 bit machine with Windows server 2012 R2

  • Freight Charges Accounting through SLA

    Dear All I have a requirement to hit different natural accounts in accounts receivable for different charges applied at order level. As all/ combine charge amount is booked in single natural account as given in autoaccounting rule - standard function

  • ABAP and SD

    Hi Friends, I have got a job in functional (SD module). I being a Software engineer have interest in programming . ABAP is what I have heard of as a language used for customization in SAP. Will it make a difference if I stick to SD module for some ti