Link to home
Start Free TrialLog in
Avatar of pronane
pronane

asked on

Jtrees in java ( click on a node and appear in the centre jpanel)

I am trying to create a GUI that has on the left pane a Jtree and on the right ( or centre ) of the GUI depending on what node in the tree has been clicked a jpanel with textfields, textareas etc will appear for example
lets say i have a jtree root called

+Test
 - Thread creation

and within the node Thread creation there is a Jtextfield where i can enter the amount of threads I want to create.  Could someone please give me some sample code, as I can only get it to work that if i click a node some text can appear in a text pane in the centre, how can i do this that i can change the configuration of the thread creation node so that if i click on another node the entered details will be there e.g sample code to test.

Thanks again,

Paul
Avatar of sct75
sct75

Do you mean that you need a Windows-Explorer-like widget where a tree on the left panel and table or other kinds of GUI on the right hand to allow user to enter in data to fields such as JTextArea, etc.
Avatar of pronane

ASKER

No like in internet explorer where frames on the left and if you click on one of the links in the frame a page will come up on the right.  But in my case I would like to go further I can get this to work in the case of lets say on the left I have a node in a JTree that says FAQ:Help and if i click that node on the right in the centre of the gui app, a jeditropane will come up with a page on FAqhelp or whatever.  What i want to do however is a new panel to appear so taht i can add certain values into that.  If you have used Jmeter version 1.8 by apache, that is a good example, on the left they have a Jtree and depending on what node you click on a Jpanel ( for exapmle ) will appear on the right that could have a jtextfield, a list, a drop down box and that if I select particular values that they will be stored so that if i click on another node and go back to taht node later the same values will still be entered.
Thanks for your explanation. I did the similar task before which requires to display different kinds of GUI layout (including Panel, ScrollPane etc.) on the right depending on user selections on the left JTree panel.

Here is what you need to do (but not limited):

0) Create a SplitPane and assign the tree to reside on the left and an empty JScrollPane or JPanel on the right as temporary place holder

1) Create GUI widget contained in JPanel or JScrollPane for each tree node command that you have. For example, one for FAQ:Help and the other for Login. You might not dynamically allocate GUI widgets, such as JTextPane, etc., on the fly easily, so at least for simplicity on the first cut, you could just create two different such panels with GUI layout.

2) Create a Tree selection listener that implements javax.swing.event.TreeSelectionListener and register it to your JTree. Let's called it MyTreeSelectionListener.


3) In this class, you create a map that you could use tree node's face value (if they are unique, otherwise, use tree node itself or some combination of paths) as the key and the GUI widget that you will display on the right as the value. When a node is clicked, your listener from 2) will be notified. Within it, you could know what tree node is clicked, which helps you lookup the map if a corresponding panel exists. If not, you could initialize one and put into the map; otherwise, you could grab that panel and put it onto the right side of the splitpane created in 0).

4) Since you use map to memorize the previous screen visited, also it will use the same instance to display on the right side of splitpane, you would see the previously entered value if switch the focus of the tree node back and forth, which I assume is what you expect.

Avatar of pronane

ASKER

Ya I get that here is what i did so far.

Ok here is my code:
class Test
{

public Test()
{

TreeSelectionListener listener =
          new TreeSelectionListener();

         
         
          // The JTree can get big, so allow it to scroll
          JScrollPane scrollpane = new JScrollPane(tree);
     
          // Display it all in a window and make the window appear
          contentPane.add(scrollpane , BorderLayout.WEST);

}

 public void valueChanged (TreeSelectionEvent event) {
      TreePath path = event.getPath();
       JTextArea texts = new JTextArea();
       contentPane.add(texts, BorderLayout.EAST);
      System.out.println ("Selected: " +
        path.getLastPathComponent());
      Object elements[] = path.getPath();
     
      for (int i=0; i<elements.length; i++) {
        System.out.print ("->" + elements[i]);
          texts.append(elements[i].toString()+ "\n");
          updateWithObject(elements[i]);
      }
      System.out.println ();
    }
  }

Right in this example I just have it printing to the console when  a particular node i selected.  What I want to do however is when a node is selected a panel not an editorpane like a jpanel ( as an example with as I said earlier   ) appears in ( contentpane.add(jpanel, BorderLayout.CENTER); ) the center. Have you any code that I can test to see this working with what u were saying?

Thanks
Let's say that you have your own frame class called TestFrame, in which you have created a JSplitPane private member variable, named mySplitPane, and put it at the center of the TestFrame's contentPane. In this frame class, you create a function, maybe, called setRightPanel(Container newContainer) (note, JPanel, JScrollPane, etc. are descendents of Container, so by using this way, you make your function generically able to take any component you'd like to put onto the right side of the splitpane but at least it should be a container) something like following,

public void setRightPanel(Container newContainer)
{
  mySplitPane.setRightComponent(newContainer);
  //following lines may or may not be necessary to force the screen refresh
  mySplitPane.invalidate();
  this.invalidate();
}

In your TreeSelectionListener class (I highly recommend using different name since this is used by java and in further conversation it might be very confusing to which one being refered), say TestTreeSelectionListener's constructor, you could take in a TestFrame parameter and suppose you have defined a member variable called myParentFrame, as following,

private TestFrame myParentFrame;
public TreeSelectionListener(TestFrame parentFrame)
{
  this.myParentFrame = parentFrame;
}

Then suppose you already defined a Map member instance in the TestTreeSelectionListener class, something like this
private Map myScreenMap = new HashMap();

Then in your valueChanged (TreeSelectionEvent event) function, and after the line with "path.getLastPathComponent());", you do following,

String command = String.valueOf(path.getLastPathComponent()));

Container container = (Container) myScreenMap.get(command);
if(container==null)
{
//create such container instance, for example,
  if("FAQ:Help".equals(command))
  {
    container = new MyFAQHelpPanel();
  }
  else if("YourOtherKindsCommands".equals(command))
  {
    ...
  }
  ...
  myScreenMap.put(command, container);
}

myParentFrame.setRightPanel(container);

...
}

Please keep in mind that in order to achieve further functionality, you should have bunch of classes that are JPanel or JScrollPanel's descendent to represent each of your screen. Also, you need couple of class to take charge of Tree Selection event and update the GUI content, acting like a controller.
Avatar of pronane

ASKER

Thanks a lot for the help will close this soon enough I just want to make sure I have it working properly I will award the points as soon as I have it working!  Thanks for the code
Avatar of pronane

ASKER

Thanks a lot for the help will close this soon enough I just want to make sure I have it working properly I will award the points as soon as I have it working!  Thanks for the code
Avatar of pronane

ASKER

Ok I implemented your code just like you said, one thing I meant ask earlier why do I need to add a JSplitpane i just want to add a panel to the centre, I tested the code so that if an item was clicked when it called:

if("Box".equals(command))
                  {
                        container = new MyFAQHelpPanel();
                  }
that within the MyFAQHelpPanel
i just had

class MyFAQHelpPanel extends JPanel
{

      public MyFAQHelpPanel()
      {
            System.out.println("hello world");
        }
}

This worked once, i.e if  i cliked on Box it would print hello world to the console once, and if i clicked on it again it wouldnt [print it again.

Then I tried to do the following:

class MyFAQHelpPanel extends JPanel
{

      public MyFAQHelpPanel()
      {JTextArea textArea = new JTextArea(
    "This is an editable JTextArea " +
         );
      textArea.setFont(new Font("Serif", Font.ITALIC, 16));
      textArea.setLineWrap(true);
      textArea.setWrapStyleWord(true);



      }
}

And nothing would appear in the centre of the Frame.  Also when I created the gui starts up in the centre of the frame there is a left button and right button as the jsplitpane why is this????

Here is my code ( if you want to run it just copy into a file called Test.java and compile and run ):

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.ButtonGroup;
import javax.swing.JMenuBar;
import javax.swing.KeyStroke;
import javax.swing.ImageIcon;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.tree.*;

import java.util.*;
/*
      http://www.oreilly.de/catalog/jfcnut/chapter/ch03.html#ch03_22.html
      https://www.experts-exchange.com/questions/20537023/JTree-problem.html
 * This class exists solely to show you what menus look like.
 * It has no menu-related event handling.
 */
public class Test extends JFrame {
    JTextArea output;
    JScrollPane scrollPane;
      Container contentPane;
      JMenuItem setLookAndfeel;
      String laf;
      JSplitPane mySplitPane;
    public Test(String lookAndFeel) {
            laf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
            String look = lookAndFeel;
            String feel = "Windows";
            String motif = "Motif";
            look = look.trim().toLowerCase();
            feel = feel.trim().toLowerCase();
            motif = motif.trim().toLowerCase();
            try
            {
                  if(look.equals(feel))
                        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                  else if(look.equals(motif))
                        UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                  else if (look.equals("Metal"))
                  {
                        UIManager.setLookAndFeel("com.sun.java.swing.plaf.metal.MetalLookAndFeel");
                  }
                  else
                  {
                        UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
                  }
            }catch(Exception e){}
            
            JMenuBar menuBar;
        JMenu menu, submenu;
        JMenuItem menuItem;
        JCheckBoxMenuItem cbMenuItem;
        JRadioButtonMenuItem rbMenuItem;
            JButton b1, b2, b3;
            JPanel buttonPanel;
            JViewport port;
            Rectangle viewPortR;
            Dimension pa;
            
      

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        //Add regular components to the window, using the default BorderLayout.
        contentPane = getContentPane();
        output = new JTextArea(5, 30);
        output.setEditable(false);
        scrollPane = new JScrollPane(output);
            JPanel panel = new JPanel();
        ImageIcon firstButtonIcon = new ImageIcon("start.gif");
            ImageIcon middleButtonIcon = new ImageIcon("stop.gif");
            ImageIcon LastButtonIcon = new ImageIcon("start.jpg");
            b1 = new JButton(firstButtonIcon);
            b1.setVerticalTextPosition(AbstractButton.BOTTOM);
            b1.setHorizontalTextPosition(AbstractButton.CENTER);
            b1.setMnemonic(KeyEvent.VK_M);

            b2 = new JButton(middleButtonIcon);
            b2.setVerticalTextPosition(AbstractButton.BOTTOM);
            b2.setHorizontalTextPosition(AbstractButton.CENTER);
            b2.setMnemonic(KeyEvent.VK_L);

            b3 = new JButton( "Last BUtton: ");
            b3.setVerticalTextPosition(AbstractButton.BOTTOM);
            b3.setHorizontalTextPosition(AbstractButton.CENTER);
            b3.setMnemonic(KeyEvent.VK_J);
            
            buttonPanel = new JPanel();
            buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
            buttonPanel.add(b1);
            buttonPanel.add(b2);
            buttonPanel.add(b3);
            contentPane.add(buttonPanel, BorderLayout.NORTH);
            
             
            JTree tree = new JTree();
            //tree.setModel();
            //tree.addTreeSelectionListener(this);
            
             DefaultMutableTreeNode component =
      new DefaultMutableTreeNode("Component");
    DefaultMutableTreeNode container =
      new DefaultMutableTreeNode("Container");
    DefaultMutableTreeNode box =
      new DefaultMutableTreeNode("Box");
    DefaultMutableTreeNode jComponent =
      new DefaultMutableTreeNode("JComponent");
    DefaultMutableTreeNode abstractButton =
      new DefaultMutableTreeNode("AbstractButton");
    DefaultMutableTreeNode jButton =
      new DefaultMutableTreeNode("JButton");
    DefaultMutableTreeNode jMenuItem =
      new DefaultMutableTreeNode("JMenuItem");
    DefaultMutableTreeNode jToggle =
      new DefaultMutableTreeNode("JToggleButton");
    DefaultMutableTreeNode jLabel =
      new DefaultMutableTreeNode("JLabel");
    DefaultMutableTreeNode etc =
      new DefaultMutableTreeNode("...");

            // Group the nodes
            component.add(container);
            container.add(box);
            container.add(jComponent);
            jComponent.add(abstractButton);
            abstractButton.add(jButton);
            abstractButton.add(jMenuItem);
            abstractButton.add(jToggle);
            jComponent.add(jLabel);
            jComponent.add(etc);


            


            TreeSelectionListener listener =
            new MyTreeSelectionListener(this);

            TreePanel tp = new TreePanel(component, listener);
            
            // The JTree can get big, so allow it to scroll
            JScrollPane scrollpane = new JScrollPane(tp);
            /*port = scrollpane.getViewport();
            viewPortR = port.getViewRect();
            int y = port.getViewSize().height;
            int x = port.getViewSize().width;
            Point p = new Point(10, 20);
            port.setViewPosition(p);
            */
            // Display it all in a window and make the window appear
            mySplitPane = new JSplitPane();
            contentPane.add(mySplitPane, BorderLayout.CENTER);
            contentPane.add(scrollpane, BorderLayout.WEST);

            //Create the menu bar.
        menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        //Build the first menu.
        menu = new JMenu("A Menu");
        menu.setMnemonic(KeyEvent.VK_A);
        menu.getAccessibleContext().setAccessibleDescription(
                "The only menu in this program that has menu items");
        menuBar.add(menu);

        //a group of JMenuItems
        menuItem = new JMenuItem("A text-only menu item",
                                 KeyEvent.VK_T);
        //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_1, ActionEvent.ALT_MASK));
        menuItem.getAccessibleContext().setAccessibleDescription(
                "This doesn't really do anything");
        menu.add(menuItem);

        menuItem = new JMenuItem("Both text and icon",
                                 new ImageIcon("images/middle.gif"));
        menuItem.setMnemonic(KeyEvent.VK_B);
        menu.add(menuItem);

        menuItem = new JMenuItem(new ImageIcon("images/middle.gif"));
        menuItem.setMnemonic(KeyEvent.VK_D);
        menu.add(menuItem);

        //a group of radio button menu items
        menu.addSeparator();
        ButtonGroup group = new ButtonGroup();

        rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
        rbMenuItem.setSelected(true);
        rbMenuItem.setMnemonic(KeyEvent.VK_R);
        group.add(rbMenuItem);
        menu.add(rbMenuItem);

        rbMenuItem = new JRadioButtonMenuItem("Another one");
        rbMenuItem.setMnemonic(KeyEvent.VK_O);
        group.add(rbMenuItem);
        menu.add(rbMenuItem);

        //a group of check box menu items
        menu.addSeparator();
        cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
        cbMenuItem.setMnemonic(KeyEvent.VK_C);
        menu.add(cbMenuItem);

        cbMenuItem = new JCheckBoxMenuItem("Another one");
        cbMenuItem.setMnemonic(KeyEvent.VK_H);
        menu.add(cbMenuItem);

        //a submenu
        menu.addSeparator();
        submenu = new JMenu("A submenu");
        submenu.setMnemonic(KeyEvent.VK_S);

        menuItem = new JMenuItem("An item in the submenu");
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_2, ActionEvent.ALT_MASK));
        submenu.add(menuItem);

        menuItem = new JMenuItem("Another item");
        submenu.add(menuItem);
        menu.add(submenu);

        JMenu edit = new JMenu("Edit");
            menuBar.add(edit);
            JMenu Run = new JMenu("Run");
            menuBar.add(Run);
            JMenu options = new JMenu("Option");
            menuBar.add(options);
            JMenu help = new JMenu("Help");
            menuBar.add(help);
            
            setLookAndfeel = new JMenuItem("Set Look and feel");
            setLookAndfeel.addActionListener(new MenuListener());
            
            options.add(setLookAndfeel);
            
   

    }
      
      public void setRightPanel(Container newContainer)
      {      
            mySplitPane.setRightComponent(newContainer);
            //following lines may or may not be necessary to force the screen refresh
            mySplitPane.invalidate();
            this.invalidate();
      }
    public static void main(String[] args) {
       
            System.out.println("Please enter the look and feel you want: (Windows, Motif, Metal) ");
            String lookAndFeel = Console.readString();
            
            Test window = new Test(lookAndFeel);
        window.setTitle("MenuLookDemo");
        window.setSize(450, 260);
        window.setVisible(true);
    }



    public class MenuListener implements ActionListener
      {
            JFileChooser fc = new JFileChooser(); //Creates a fileChooser to open & save files etc.

            public void actionPerformed(ActionEvent event)
            {

                  Object source = event.getSource();
      
                  if(source == setLookAndfeel)
                  {
                        try
                        {
                              System.out.println("got here");
                              
                              String laf = "Metal";
                              Test p = new Test(laf);
                        }catch(Exception e){}
                  }      
          }
      }

 class MyTreeSelectionListener implements TreeSelectionListener {
     private Map myScreenMap = new HashMap();
       private Test myParentFrame;
       public MyTreeSelectionListener(Test parentFrame)
       {
            this.myParentFrame = parentFrame;
       }
       public void valueChanged (TreeSelectionEvent event)
       {
            TreePath path = event.getPath();
            JTextArea texts = new JTextArea();
          contentPane.add(texts, BorderLayout.EAST);
            System.out.println ("Selected: " + path.getLastPathComponent());
            String command = String.valueOf(path.getLastPathComponent());
      
        
            Container container = (Container) myScreenMap.get(command);
            if(container==null)
            {
                  //create such container instance, for example,
                  if("Box".equals(command))
                  {
                        container = new MyFAQHelpPanel();
                  }
                  else if("YourOtherKindsCommands".equals(command))
                  {
                  
                  }
                  myScreenMap.put(command, container);
            }

            myParentFrame.setRightPanel(container);

            
            Object elements[] = path.getPath();
      
            for (int i=0; i<elements.length; i++) {
        System.out.print ("->" + elements[i]);
            texts.append(elements[i].toString()+ "\n");
            updateWithObject(elements[i]);
      }
            System.out.println ();
    }
  }
  public void updateWithObject(Object o)
      {

      }
}
class MyFAQHelpPanel extends JPanel
{

      public MyFAQHelpPanel()
      {JTextArea textArea = new JTextArea(
    "This is an editable JTextArea " +
    "that has been initialized with the setText method. " +
    "A text area is a \"plain\" text component, " +
    "which means that although it can display text " +
    "in any font, all of the text is in the same font."
      );
      textArea.setFont(new Font("Serif", Font.ITALIC, 16));
      textArea.setLineWrap(true);
      textArea.setWrapStyleWord(true);



      }
}
Avatar of pronane

ASKER

Ok I implemented your code just like you said, one thing I meant ask earlier why do I need to add a JSplitpane i just want to add a panel to the centre, I tested the code so that if an item was clicked when it called:

if("Box".equals(command))
                  {
                        container = new MyFAQHelpPanel();
                  }
that within the MyFAQHelpPanel
i just had

class MyFAQHelpPanel extends JPanel
{

      public MyFAQHelpPanel()
      {
            System.out.println("hello world");
        }
}

This worked once, i.e if  i cliked on Box it would print hello world to the console once, and if i clicked on it again it wouldnt [print it again.

Then I tried to do the following:

class MyFAQHelpPanel extends JPanel
{

      public MyFAQHelpPanel()
      {JTextArea textArea = new JTextArea(
    "This is an editable JTextArea " +
         );
      textArea.setFont(new Font("Serif", Font.ITALIC, 16));
      textArea.setLineWrap(true);
      textArea.setWrapStyleWord(true);



      }
}

And nothing would appear in the centre of the Frame.  Also when I created the gui starts up in the centre of the frame there is a left button and right button as the jsplitpane why is this????

Here is my code ( if you want to run it just copy into a file called Test.java and compile and run ):

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.ButtonGroup;
import javax.swing.JMenuBar;
import javax.swing.KeyStroke;
import javax.swing.ImageIcon;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.tree.*;

import java.util.*;
/*
      http://www.oreilly.de/catalog/jfcnut/chapter/ch03.html#ch03_22.html
      https://www.experts-exchange.com/questions/20537023/JTree-problem.html
 * This class exists solely to show you what menus look like.
 * It has no menu-related event handling.
 */
public class Test extends JFrame {
    JTextArea output;
    JScrollPane scrollPane;
      Container contentPane;
      JMenuItem setLookAndfeel;
      String laf;
      JSplitPane mySplitPane;
    public Test(String lookAndFeel) {
            laf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
            String look = lookAndFeel;
            String feel = "Windows";
            String motif = "Motif";
            look = look.trim().toLowerCase();
            feel = feel.trim().toLowerCase();
            motif = motif.trim().toLowerCase();
            try
            {
                  if(look.equals(feel))
                        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                  else if(look.equals(motif))
                        UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                  else if (look.equals("Metal"))
                  {
                        UIManager.setLookAndFeel("com.sun.java.swing.plaf.metal.MetalLookAndFeel");
                  }
                  else
                  {
                        UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
                  }
            }catch(Exception e){}
            
            JMenuBar menuBar;
        JMenu menu, submenu;
        JMenuItem menuItem;
        JCheckBoxMenuItem cbMenuItem;
        JRadioButtonMenuItem rbMenuItem;
            JButton b1, b2, b3;
            JPanel buttonPanel;
            JViewport port;
            Rectangle viewPortR;
            Dimension pa;
            
      

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        //Add regular components to the window, using the default BorderLayout.
        contentPane = getContentPane();
        output = new JTextArea(5, 30);
        output.setEditable(false);
        scrollPane = new JScrollPane(output);
            JPanel panel = new JPanel();
        ImageIcon firstButtonIcon = new ImageIcon("start.gif");
            ImageIcon middleButtonIcon = new ImageIcon("stop.gif");
            ImageIcon LastButtonIcon = new ImageIcon("start.jpg");
            b1 = new JButton(firstButtonIcon);
            b1.setVerticalTextPosition(AbstractButton.BOTTOM);
            b1.setHorizontalTextPosition(AbstractButton.CENTER);
            b1.setMnemonic(KeyEvent.VK_M);

            b2 = new JButton(middleButtonIcon);
            b2.setVerticalTextPosition(AbstractButton.BOTTOM);
            b2.setHorizontalTextPosition(AbstractButton.CENTER);
            b2.setMnemonic(KeyEvent.VK_L);

            b3 = new JButton( "Last BUtton: ");
            b3.setVerticalTextPosition(AbstractButton.BOTTOM);
            b3.setHorizontalTextPosition(AbstractButton.CENTER);
            b3.setMnemonic(KeyEvent.VK_J);
            
            buttonPanel = new JPanel();
            buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
            buttonPanel.add(b1);
            buttonPanel.add(b2);
            buttonPanel.add(b3);
            contentPane.add(buttonPanel, BorderLayout.NORTH);
            
             
            JTree tree = new JTree();
            //tree.setModel();
            //tree.addTreeSelectionListener(this);
            
             DefaultMutableTreeNode component =
      new DefaultMutableTreeNode("Component");
    DefaultMutableTreeNode container =
      new DefaultMutableTreeNode("Container");
    DefaultMutableTreeNode box =
      new DefaultMutableTreeNode("Box");
    DefaultMutableTreeNode jComponent =
      new DefaultMutableTreeNode("JComponent");
    DefaultMutableTreeNode abstractButton =
      new DefaultMutableTreeNode("AbstractButton");
    DefaultMutableTreeNode jButton =
      new DefaultMutableTreeNode("JButton");
    DefaultMutableTreeNode jMenuItem =
      new DefaultMutableTreeNode("JMenuItem");
    DefaultMutableTreeNode jToggle =
      new DefaultMutableTreeNode("JToggleButton");
    DefaultMutableTreeNode jLabel =
      new DefaultMutableTreeNode("JLabel");
    DefaultMutableTreeNode etc =
      new DefaultMutableTreeNode("...");

            // Group the nodes
            component.add(container);
            container.add(box);
            container.add(jComponent);
            jComponent.add(abstractButton);
            abstractButton.add(jButton);
            abstractButton.add(jMenuItem);
            abstractButton.add(jToggle);
            jComponent.add(jLabel);
            jComponent.add(etc);


            


            TreeSelectionListener listener =
            new MyTreeSelectionListener(this);

            TreePanel tp = new TreePanel(component, listener);
            
            // The JTree can get big, so allow it to scroll
            JScrollPane scrollpane = new JScrollPane(tp);
            /*port = scrollpane.getViewport();
            viewPortR = port.getViewRect();
            int y = port.getViewSize().height;
            int x = port.getViewSize().width;
            Point p = new Point(10, 20);
            port.setViewPosition(p);
            */
            // Display it all in a window and make the window appear
            mySplitPane = new JSplitPane();
            contentPane.add(mySplitPane, BorderLayout.CENTER);
            contentPane.add(scrollpane, BorderLayout.WEST);

            //Create the menu bar.
        menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        //Build the first menu.
        menu = new JMenu("A Menu");
        menu.setMnemonic(KeyEvent.VK_A);
        menu.getAccessibleContext().setAccessibleDescription(
                "The only menu in this program that has menu items");
        menuBar.add(menu);

        //a group of JMenuItems
        menuItem = new JMenuItem("A text-only menu item",
                                 KeyEvent.VK_T);
        //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_1, ActionEvent.ALT_MASK));
        menuItem.getAccessibleContext().setAccessibleDescription(
                "This doesn't really do anything");
        menu.add(menuItem);

        menuItem = new JMenuItem("Both text and icon",
                                 new ImageIcon("images/middle.gif"));
        menuItem.setMnemonic(KeyEvent.VK_B);
        menu.add(menuItem);

        menuItem = new JMenuItem(new ImageIcon("images/middle.gif"));
        menuItem.setMnemonic(KeyEvent.VK_D);
        menu.add(menuItem);

        //a group of radio button menu items
        menu.addSeparator();
        ButtonGroup group = new ButtonGroup();

        rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
        rbMenuItem.setSelected(true);
        rbMenuItem.setMnemonic(KeyEvent.VK_R);
        group.add(rbMenuItem);
        menu.add(rbMenuItem);

        rbMenuItem = new JRadioButtonMenuItem("Another one");
        rbMenuItem.setMnemonic(KeyEvent.VK_O);
        group.add(rbMenuItem);
        menu.add(rbMenuItem);

        //a group of check box menu items
        menu.addSeparator();
        cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
        cbMenuItem.setMnemonic(KeyEvent.VK_C);
        menu.add(cbMenuItem);

        cbMenuItem = new JCheckBoxMenuItem("Another one");
        cbMenuItem.setMnemonic(KeyEvent.VK_H);
        menu.add(cbMenuItem);

        //a submenu
        menu.addSeparator();
        submenu = new JMenu("A submenu");
        submenu.setMnemonic(KeyEvent.VK_S);

        menuItem = new JMenuItem("An item in the submenu");
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_2, ActionEvent.ALT_MASK));
        submenu.add(menuItem);

        menuItem = new JMenuItem("Another item");
        submenu.add(menuItem);
        menu.add(submenu);

        JMenu edit = new JMenu("Edit");
            menuBar.add(edit);
            JMenu Run = new JMenu("Run");
            menuBar.add(Run);
            JMenu options = new JMenu("Option");
            menuBar.add(options);
            JMenu help = new JMenu("Help");
            menuBar.add(help);
            
            setLookAndfeel = new JMenuItem("Set Look and feel");
            setLookAndfeel.addActionListener(new MenuListener());
            
            options.add(setLookAndfeel);
            
   

    }
      
      public void setRightPanel(Container newContainer)
      {      
            mySplitPane.setRightComponent(newContainer);
            //following lines may or may not be necessary to force the screen refresh
            mySplitPane.invalidate();
            this.invalidate();
      }
    public static void main(String[] args) {
       
            System.out.println("Please enter the look and feel you want: (Windows, Motif, Metal) ");
            String lookAndFeel = Console.readString();
            
            Test window = new Test(lookAndFeel);
        window.setTitle("MenuLookDemo");
        window.setSize(450, 260);
        window.setVisible(true);
    }



    public class MenuListener implements ActionListener
      {
            JFileChooser fc = new JFileChooser(); //Creates a fileChooser to open & save files etc.

            public void actionPerformed(ActionEvent event)
            {

                  Object source = event.getSource();
      
                  if(source == setLookAndfeel)
                  {
                        try
                        {
                              System.out.println("got here");
                              
                              String laf = "Metal";
                              Test p = new Test(laf);
                        }catch(Exception e){}
                  }      
          }
      }

 class MyTreeSelectionListener implements TreeSelectionListener {
     private Map myScreenMap = new HashMap();
       private Test myParentFrame;
       public MyTreeSelectionListener(Test parentFrame)
       {
            this.myParentFrame = parentFrame;
       }
       public void valueChanged (TreeSelectionEvent event)
       {
            TreePath path = event.getPath();
            JTextArea texts = new JTextArea();
          contentPane.add(texts, BorderLayout.EAST);
            System.out.println ("Selected: " + path.getLastPathComponent());
            String command = String.valueOf(path.getLastPathComponent());
      
        
            Container container = (Container) myScreenMap.get(command);
            if(container==null)
            {
                  //create such container instance, for example,
                  if("Box".equals(command))
                  {
                        container = new MyFAQHelpPanel();
                  }
                  else if("YourOtherKindsCommands".equals(command))
                  {
                  
                  }
                  myScreenMap.put(command, container);
            }

            myParentFrame.setRightPanel(container);

            
            Object elements[] = path.getPath();
      
            for (int i=0; i<elements.length; i++) {
        System.out.print ("->" + elements[i]);
            texts.append(elements[i].toString()+ "\n");
            updateWithObject(elements[i]);
      }
            System.out.println ();
    }
  }
  public void updateWithObject(Object o)
      {

      }
}
class MyFAQHelpPanel extends JPanel
{

      public MyFAQHelpPanel()
      {JTextArea textArea = new JTextArea(
    "This is an editable JTextArea " +
    "that has been initialized with the setText method. " +
    "A text area is a \"plain\" text component, " +
    "which means that although it can display text " +
    "in any font, all of the text is in the same font."
      );
      textArea.setFont(new Font("Serif", Font.ITALIC, 16));
      textArea.setLineWrap(true);
      textArea.setWrapStyleWord(true);



      }
}
Avatar of pronane

ASKER

Ok I implemented your code just like you said, one thing I meant ask earlier why do I need to add a JSplitpane i just want to add a panel to the centre, I tested the code so that if an item was clicked when it called:

if("Box".equals(command))
                  {
                        container = new MyFAQHelpPanel();
                  }
that within the MyFAQHelpPanel
i just had

class MyFAQHelpPanel extends JPanel
{

      public MyFAQHelpPanel()
      {
            System.out.println("hello world");
        }
}

This worked once, i.e if  i cliked on Box it would print hello world to the console once, and if i clicked on it again it wouldnt [print it again.

Then I tried to do the following:

class MyFAQHelpPanel extends JPanel
{

      public MyFAQHelpPanel()
      {JTextArea textArea = new JTextArea(
    "This is an editable JTextArea " +
         );
      textArea.setFont(new Font("Serif", Font.ITALIC, 16));
      textArea.setLineWrap(true);
      textArea.setWrapStyleWord(true);



      }
}

And nothing would appear in the centre of the Frame.  Also when I created the gui starts up in the centre of the frame there is a left button and right button as the jsplitpane why is this????

Here is my code ( if you want to run it just copy into a file called Test.java and compile and run ):

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.ButtonGroup;
import javax.swing.JMenuBar;
import javax.swing.KeyStroke;
import javax.swing.ImageIcon;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.tree.*;

import java.util.*;
/*
      http://www.oreilly.de/catalog/jfcnut/chapter/ch03.html#ch03_22.html
      https://www.experts-exchange.com/questions/20537023/JTree-problem.html
 * This class exists solely to show you what menus look like.
 * It has no menu-related event handling.
 */
public class Test extends JFrame {
    JTextArea output;
    JScrollPane scrollPane;
      Container contentPane;
      JMenuItem setLookAndfeel;
      String laf;
      JSplitPane mySplitPane;
    public Test(String lookAndFeel) {
            laf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
            String look = lookAndFeel;
            String feel = "Windows";
            String motif = "Motif";
            look = look.trim().toLowerCase();
            feel = feel.trim().toLowerCase();
            motif = motif.trim().toLowerCase();
            try
            {
                  if(look.equals(feel))
                        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                  else if(look.equals(motif))
                        UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                  else if (look.equals("Metal"))
                  {
                        UIManager.setLookAndFeel("com.sun.java.swing.plaf.metal.MetalLookAndFeel");
                  }
                  else
                  {
                        UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
                  }
            }catch(Exception e){}
            
            JMenuBar menuBar;
        JMenu menu, submenu;
        JMenuItem menuItem;
        JCheckBoxMenuItem cbMenuItem;
        JRadioButtonMenuItem rbMenuItem;
            JButton b1, b2, b3;
            JPanel buttonPanel;
            JViewport port;
            Rectangle viewPortR;
            Dimension pa;
            
      

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        //Add regular components to the window, using the default BorderLayout.
        contentPane = getContentPane();
        output = new JTextArea(5, 30);
        output.setEditable(false);
        scrollPane = new JScrollPane(output);
            JPanel panel = new JPanel();
        ImageIcon firstButtonIcon = new ImageIcon("start.gif");
            ImageIcon middleButtonIcon = new ImageIcon("stop.gif");
            ImageIcon LastButtonIcon = new ImageIcon("start.jpg");
            b1 = new JButton(firstButtonIcon);
            b1.setVerticalTextPosition(AbstractButton.BOTTOM);
            b1.setHorizontalTextPosition(AbstractButton.CENTER);
            b1.setMnemonic(KeyEvent.VK_M);

            b2 = new JButton(middleButtonIcon);
            b2.setVerticalTextPosition(AbstractButton.BOTTOM);
            b2.setHorizontalTextPosition(AbstractButton.CENTER);
            b2.setMnemonic(KeyEvent.VK_L);

            b3 = new JButton( "Last BUtton: ");
            b3.setVerticalTextPosition(AbstractButton.BOTTOM);
            b3.setHorizontalTextPosition(AbstractButton.CENTER);
            b3.setMnemonic(KeyEvent.VK_J);
            
            buttonPanel = new JPanel();
            buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
            buttonPanel.add(b1);
            buttonPanel.add(b2);
            buttonPanel.add(b3);
            contentPane.add(buttonPanel, BorderLayout.NORTH);
            
             
            JTree tree = new JTree();
            //tree.setModel();
            //tree.addTreeSelectionListener(this);
            
             DefaultMutableTreeNode component =
      new DefaultMutableTreeNode("Component");
    DefaultMutableTreeNode container =
      new DefaultMutableTreeNode("Container");
    DefaultMutableTreeNode box =
      new DefaultMutableTreeNode("Box");
    DefaultMutableTreeNode jComponent =
      new DefaultMutableTreeNode("JComponent");
    DefaultMutableTreeNode abstractButton =
      new DefaultMutableTreeNode("AbstractButton");
    DefaultMutableTreeNode jButton =
      new DefaultMutableTreeNode("JButton");
    DefaultMutableTreeNode jMenuItem =
      new DefaultMutableTreeNode("JMenuItem");
    DefaultMutableTreeNode jToggle =
      new DefaultMutableTreeNode("JToggleButton");
    DefaultMutableTreeNode jLabel =
      new DefaultMutableTreeNode("JLabel");
    DefaultMutableTreeNode etc =
      new DefaultMutableTreeNode("...");

            // Group the nodes
            component.add(container);
            container.add(box);
            container.add(jComponent);
            jComponent.add(abstractButton);
            abstractButton.add(jButton);
            abstractButton.add(jMenuItem);
            abstractButton.add(jToggle);
            jComponent.add(jLabel);
            jComponent.add(etc);


            


            TreeSelectionListener listener =
            new MyTreeSelectionListener(this);

            TreePanel tp = new TreePanel(component, listener);
            
            // The JTree can get big, so allow it to scroll
            JScrollPane scrollpane = new JScrollPane(tp);
            /*port = scrollpane.getViewport();
            viewPortR = port.getViewRect();
            int y = port.getViewSize().height;
            int x = port.getViewSize().width;
            Point p = new Point(10, 20);
            port.setViewPosition(p);
            */
            // Display it all in a window and make the window appear
            mySplitPane = new JSplitPane();
            contentPane.add(mySplitPane, BorderLayout.CENTER);
            contentPane.add(scrollpane, BorderLayout.WEST);

            //Create the menu bar.
        menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        //Build the first menu.
        menu = new JMenu("A Menu");
        menu.setMnemonic(KeyEvent.VK_A);
        menu.getAccessibleContext().setAccessibleDescription(
                "The only menu in this program that has menu items");
        menuBar.add(menu);

        //a group of JMenuItems
        menuItem = new JMenuItem("A text-only menu item",
                                 KeyEvent.VK_T);
        //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_1, ActionEvent.ALT_MASK));
        menuItem.getAccessibleContext().setAccessibleDescription(
                "This doesn't really do anything");
        menu.add(menuItem);

        menuItem = new JMenuItem("Both text and icon",
                                 new ImageIcon("images/middle.gif"));
        menuItem.setMnemonic(KeyEvent.VK_B);
        menu.add(menuItem);

        menuItem = new JMenuItem(new ImageIcon("images/middle.gif"));
        menuItem.setMnemonic(KeyEvent.VK_D);
        menu.add(menuItem);

        //a group of radio button menu items
        menu.addSeparator();
        ButtonGroup group = new ButtonGroup();

        rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
        rbMenuItem.setSelected(true);
        rbMenuItem.setMnemonic(KeyEvent.VK_R);
        group.add(rbMenuItem);
        menu.add(rbMenuItem);

        rbMenuItem = new JRadioButtonMenuItem("Another one");
        rbMenuItem.setMnemonic(KeyEvent.VK_O);
        group.add(rbMenuItem);
        menu.add(rbMenuItem);

        //a group of check box menu items
        menu.addSeparator();
        cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
        cbMenuItem.setMnemonic(KeyEvent.VK_C);
        menu.add(cbMenuItem);

        cbMenuItem = new JCheckBoxMenuItem("Another one");
        cbMenuItem.setMnemonic(KeyEvent.VK_H);
        menu.add(cbMenuItem);

        //a submenu
        menu.addSeparator();
        submenu = new JMenu("A submenu");
        submenu.setMnemonic(KeyEvent.VK_S);

        menuItem = new JMenuItem("An item in the submenu");
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_2, ActionEvent.ALT_MASK));
        submenu.add(menuItem);

        menuItem = new JMenuItem("Another item");
        submenu.add(menuItem);
        menu.add(submenu);

        JMenu edit = new JMenu("Edit");
            menuBar.add(edit);
            JMenu Run = new JMenu("Run");
            menuBar.add(Run);
            JMenu options = new JMenu("Option");
            menuBar.add(options);
            JMenu help = new JMenu("Help");
            menuBar.add(help);
            
            setLookAndfeel = new JMenuItem("Set Look and feel");
            setLookAndfeel.addActionListener(new MenuListener());
            
            options.add(setLookAndfeel);
            
   

    }
      
      public void setRightPanel(Container newContainer)
      {      
            mySplitPane.setRightComponent(newContainer);
            //following lines may or may not be necessary to force the screen refresh
            mySplitPane.invalidate();
            this.invalidate();
      }
    public static void main(String[] args) {
       
            System.out.println("Please enter the look and feel you want: (Windows, Motif, Metal) ");
            String lookAndFeel = Console.readString();
            
            Test window = new Test(lookAndFeel);
        window.setTitle("MenuLookDemo");
        window.setSize(450, 260);
        window.setVisible(true);
    }



    public class MenuListener implements ActionListener
      {
            JFileChooser fc = new JFileChooser(); //Creates a fileChooser to open & save files etc.

            public void actionPerformed(ActionEvent event)
            {

                  Object source = event.getSource();
      
                  if(source == setLookAndfeel)
                  {
                        try
                        {
                              System.out.println("got here");
                              
                              String laf = "Metal";
                              Test p = new Test(laf);
                        }catch(Exception e){}
                  }      
          }
      }

 class MyTreeSelectionListener implements TreeSelectionListener {
     private Map myScreenMap = new HashMap();
       private Test myParentFrame;
       public MyTreeSelectionListener(Test parentFrame)
       {
            this.myParentFrame = parentFrame;
       }
       public void valueChanged (TreeSelectionEvent event)
       {
            TreePath path = event.getPath();
            JTextArea texts = new JTextArea();
          contentPane.add(texts, BorderLayout.EAST);
            System.out.println ("Selected: " + path.getLastPathComponent());
            String command = String.valueOf(path.getLastPathComponent());
      
        
            Container container = (Container) myScreenMap.get(command);
            if(container==null)
            {
                  //create such container instance, for example,
                  if("Box".equals(command))
                  {
                        container = new MyFAQHelpPanel();
                  }
                  else if("YourOtherKindsCommands".equals(command))
                  {
                  
                  }
                  myScreenMap.put(command, container);
            }

            myParentFrame.setRightPanel(container);

            
            Object elements[] = path.getPath();
      
            for (int i=0; i<elements.length; i++) {
        System.out.print ("->" + elements[i]);
            texts.append(elements[i].toString()+ "\n");
            updateWithObject(elements[i]);
      }
            System.out.println ();
    }
  }
  public void updateWithObject(Object o)
      {

      }
}
class MyFAQHelpPanel extends JPanel
{

      public MyFAQHelpPanel()
      {JTextArea textArea = new JTextArea(
    "This is an editable JTextArea " +
    "that has been initialized with the setText method. " +
    "A text area is a \"plain\" text component, " +
    "which means that although it can display text " +
    "in any font, all of the text is in the same font."
      );
      textArea.setFont(new Font("Serif", Font.ITALIC, 16));
      textArea.setLineWrap(true);
      textArea.setWrapStyleWord(true);



      }
}
Avatar of pronane

ASKER

sorry about the three previous (multiple) posts something this side I couldnt help and had to press refresh without realising!
Avatar of pronane

ASKER

class MyFAQHelpPanel should look like this:

class MyFAQHelpPanel extends JPanel
{
     JPanel aPanel;
 
     public MyFAQHelpPanel()
     {
          aPanel = new JPanel(new BorderLayout());
          System.out.println("Hello");
         
          JTextArea textArea = new JTextArea(
    "This is an editable JTextArea " +
    "that has been initialized with the setText method. " +
    "A text area is a \"plain\" text component, " +
    "which means that although it can display text " +
    "in any font, all of the text is in the same font."
     );
     textArea.setFont(new Font("Serif", Font.ITALIC, 16));
     textArea.setLineWrap(true);
     textArea.setWrapStyleWord(true);

           
      aPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);
     
     
     }
}
Could I get back to you after this weekend? Thanks.
First, I think the GUI layout in the center of your frame should be a splitpane, in which your TreePanel resides on the left and your future displayable panel (based on user command) resides on the right.

To put your TreePanel to the left of splitpane, you call splitpane.setLeftComponent(). And your existing setRightPanel() function helps switch the display panels on the right.

Here is a revised version of the setRightPanel() that you could try if the panels do not show up when repeat toggling.

public void setRightPanel(Container newContainer)
{    
Component oldRightComp = mySplitPane.getRightComponent();
if(oldRightComp!=null)
{
mySplitPane.remove(oldRightComp);
}
newContainer.setVisible(true);
mySplitPane.setRightComponent(newContainer);

//following lines may or may not be necessary to force the screen refresh
mySplitPane.invalidate();
this.invalidate();
}


Last, you'd better put in a dummy (empty) JPanel to the right of JSplitPane when the program starts in order to avoid the "Right Button" showing on the right side of JSplitPane. Since your Tree Panel already occupies the left side of the JSplitPane during initiation, the "Left Button" sign will not display anymore.

Good luck.
Avatar of pronane

ASKER

This must appear like spoon feeding! But I have another problem, I did waht you said, I changed it aroung as well taht i added the splitpane to the center of the contentpane and move the tree as the left hand component of the of splitpane, that works fine.  But now if I click on anyhow of the nodes in the tree I get a null pointer exception!

Here it is:
Selected: Container   //thats what I print out so that i know what is selected
java.lang.NullPointerException
        at Test.setRightPanel(Test.java:408)
        at Test$MyTreeSelectionListener.valueChanged(Test.java:482)
        at javax.swing.JTree.fireValueChanged(JTree.java:2402)
        at javax.swing.JTree$TreeSelectionRedirector.valueChanged(JTree.java:277
3)
        at javax.swing.tree.DefaultTreeSelectionModel.fireValueChanged(DefaultTr
eeSelectionModel.java:629)
        at javax.swing.tree.DefaultTreeSelectionModel.notifyPathChange(DefaultTr
eeSelectionModel.java:1071)
        at javax.swing.tree.DefaultTreeSelectionModel.addSelectionPaths(DefaultT
reeSelectionModel.java:406)
        at javax.swing.tree.DefaultTreeSelectionModel.addSelectionPath(DefaultTr
eeSelectionModel.java:303)
        at javax.swing.JTree.addSelectionPath(JTree.java:1281)
        at javax.swing.JTree.setExpandedState(JTree.java:2989)
        at javax.swing.JTree.collapsePath(JTree.java:1769)
        at javax.swing.plaf.basic.BasicTreeUI.toggleExpandState(BasicTreeUI.java
:2104)
        at javax.swing.plaf.basic.BasicTreeUI.handleExpandControlClick(BasicTree
UI.java:2080)
        at javax.swing.plaf.basic.BasicTreeUI.checkForClickInExpandControl(Basic
TreeUI.java:2034)
        at javax.swing.plaf.basic.BasicTreeUI$MouseHandler.handleSelection(Basic
TreeUI.java:2809)
        at javax.swing.plaf.basic.BasicTreeUI$MouseHandler.mousePressed(BasicTre
eUI.java:2779)
        at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:21
8)
        at java.awt.Component.processMouseEvent(Component.java:5018)
        at java.awt.Component.processEvent(Component.java:4818)
        at java.awt.Container.processEvent(Container.java:1525)
        at java.awt.Component.dispatchEventImpl(Component.java:3526)
        at java.awt.Container.dispatchEventImpl(Container.java:1582)
        at java.awt.Component.dispatchEvent(Component.java:3367)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3359
)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3071)

        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3004)
        at java.awt.Container.dispatchEventImpl(Container.java:1568)
        at java.awt.Window.dispatchEventImpl(Window.java:1581)
        at java.awt.Component.dispatchEvent(Component.java:3367)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:445)
        at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
read.java:191)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
ad.java:144)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)

        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)

        at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)

And its not adding the Jpanel to the right component correctly.  Im obviously not doing something right but what im not sure!!  I can post the code again if you want to see and run it.  

Thanks a lot for all the help, much appreciated.
Avatar of pronane

ASKER

Sorry just fixed that part:
it was to do with this line in the setRightPanel method

newContainer.setVisible(true);

But it stilll isnt paiintin the panel its just blank.  However when i click on the "box" node the right button disappears and a panel is definatley being created as its no longer a button, I dont think I am adding components to the panel correctly.  Does this class look alright:

class MyFAQHelpPanel extends JPanel
{
     JPanel aPanel;
 
     public MyFAQHelpPanel()
     {
          aPanel = new JPanel(new BorderLayout());
          System.out.println("Hello");
         
          JTextArea textArea = new JTextArea(
    "This is an editable JTextArea " +
    "that has been initialized with the setText method. " +
    "A text area is a \"plain\" text component, " +
    "which means that although it can display text " +
    "in any font, all of the text is in the same font."
     );
     textArea.setFont(new Font("Serif", Font.ITALIC, 16));
     textArea.setLineWrap(true);
     textArea.setWrapStyleWord(true);

           
      aPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);
     
     
     }
}
Avatar of pronane

ASKER

Just to let you know again, I tried to just set the rightcomponent in the test frame to the following:

mySplitPane.setRightComponent(MyFAQHelpPanel() );

it just did the same as when calling the class once the Box node in the tree is clicked, but as usual the right button didnt appear so it appears to be doing something am I adding things to the panel in that class incorrectly or what?  I also tried to make myfaqhelppanel a method of type component and pass it in the parameters of the setRightComponent, but it still didnt fraw the panel, any ideas to what I am NOT doing?? When you get a chance to answer this I will be very happy!!!

Thanks again,

Paul
Avatar of pronane

ASKER

Is this post getting modified, and seen by users cause a friend of mine has gone through all the questions and cant see this one!!

anyone got any idea on this question if they have seen it???

Thanks
Here is the code from your previous post. Within your MyFAQHelpPanel class you have an instance variable aPanel, and you put everything onto that panel, but you did not put it onto your instance of MyFAQHelpPanel, which means when you instantiate an instance of MyFAQHelpPanel, there is nothing on it! Two solutions. One is to add following two lines in the proper location of your following code,

this.setLayout(new BorderLayout());
this.add(aPanel, BorderLayout.CENTER);

The other is to completely abandon aPanel instance and add all GUI component directly to the MyFAQHelpPanel, so replace what you have on aPanel. to this., then it should work.

Additionally, after correcting this, you might give it try to bring "newContainer.setVisible(true);" back to the setRightPanel() method or add a "if(newContainer!=null)" in front of it as checking.




class MyFAQHelpPanel extends JPanel
{
    JPanel aPanel;
 
    public MyFAQHelpPanel()
    {
         aPanel = new JPanel(new BorderLayout());
         System.out.println("Hello");
         
         JTextArea textArea = new JTextArea(
   "This is an editable JTextArea " +
   "that has been initialized with the setText method. " +
   "A text area is a \"plain\" text component, " +
   "which means that although it can display text " +
   "in any font, all of the text is in the same font."
    );
    textArea.setFont(new Font("Serif", Font.ITALIC, 16));
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);

         
     aPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);
     
     
    }
}
I think your friends need to search deep down the chain instead of from the first couple of pages of "Language" section in order to find this post because it is not a new one to date.
Avatar of pronane

ASKER

I am not fully sure what you mean in your first solution.


You wont be able to add this because the instance is in the treeselectionlistener class and a new instance gets created every time something is clicked.

this.setLayout(new BorderLayout());
this.add(aPanel, BorderLayout.CENTER);

what am I supposed to be adding the aPanel too?  

the other solution you are saying is to manually add all the components to the constructor like such:

public MyFAQHelpPAnel(Jtextarea texarea, etc)

then initialise it in hte constructor, is that correct?  I tried that before but it didnt work.

Thanks.
Avatar of pronane

ASKER

Tried both things there by setting the layout in my test class and adding components directly neither worked.  I dont know if I am doing something wrong or if so what, because I know of other colleagues saying the same thing when using splitpanes, that this can be a problem.  IS there something I could post to help?  Tired eyes and a tired mind are failing me at this point!
ASKER CERTIFIED SOLUTION
Avatar of sct75
sct75

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pronane

ASKER

Ya the hello print out was always printing to the screen that is why I thought the problem was with MyFaqHelppanel class, the second solution worked fine and dandy, thanks very much for all you put into this, I have another problem now, that the jtextarea takes up the whole screen so i have to keep resizing if you know off hand the solution I would greatly appreciate it, otherwise dont worry ill figure it out.

Ill assign the points to you soon.

Thanks again for the help and the time,

Paul

Your Textarea takes up all the screen because you used BorderLayout for your panel and add your textarea to it by BorderLayout.CENTER.

If you don't want to do so, you need to change the layout manger of your MyFaqHelppanel to something else or put a huge empty JPanel on the NORTH and SOUTH of MyFaqHelppanel to kind of squeeze the text area to the "center" as you want.

Good luck.
Avatar of pronane

ASKER

Very good answer, he spent a lot of time explaining things as well. Thanks a lot