Re: JTree problem

You should look at the TreeSelectionListener class.
public class MyFrame extends JFrame implements TreeSelectionListner {
JTree tree = ...;
public MyFrame() {
super();
tree.addTreeSelectionListener(this);
public void valueChanged(TreeSelectionEvent evt) {
// put your code here
}

Deat 7rst,
Sorry, I want to ask you about the same problem.
if I want to display a difference components from difference node in JTree, how the code I must use?
I already understand about the code that you give to me. But I still confuse if many nodes in JTree to perform difference panel with many components each of its. The components beside JTextField.

Similar Messages

  • An Expandable JTree Problem

    Hi, I'm relatively new to creating JTree components, now I have looked at many examples, and this one is nearest (i can see) to how I want my Jtree to look, however it doesn't behave in a way which I would like!
    Firstly, I can set the root node to have as many folders as i want, however they only mirror whats in the first root node, I dont want this - I want to be able to create about 5/6 different roots that will yield different results - I also want after each time you click on a folder, which will ask a question about a patient i.e. "Has the patient a head injury" - click on this then it should come up with "3" more different choices, so altogther want it about 5 deep.
    However, this is what I've got so far - but like I say, its not yielding the results I want, does anyone know how to modify this or can anyone point me in the right direction by starting me off a bit, that would be great!
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    public class SelectableTree extends JFrame
                                implements TreeSelectionListener {
      public static void main(String[] args) {
        new SelectableTree();
      private JTree tree;
      private JTextField currentSelectionField;
      public SelectableTree() {
        super("Clinical Information Help System");
        WindowUtilities.setNativeLookAndFeel();
        addWindowListener(new ExitListener());
        Container content = getContentPane();
        DefaultMutableTreeNode root =
          new DefaultMutableTreeNode("Begin Clinical Questions");
        DefaultMutableTreeNode child = null;
        DefaultMutableTreeNode parent = null;
        DefaultMutableTreeNode grandChild = null;
        DefaultMutableTreeNode grandParent = null;
        DefaultMutableTreeNode child2 = null;
        DefaultMutableTreeNode parents = null;
        for(int grandParentIndex=1; grandParentIndex < 2; grandParentIndex++) {
          grandParent = new DefaultMutableTreeNode("[Does Patient Have Back Pains?] " + grandParentIndex);
          root.add(grandParent);
          for(int parentIndex =1; parentIndex < 3; parentIndex++) {
            parent = new DefaultMutableTreeNode("[Does the patient also have leg pain?] " + parentIndex +
                                         "." + parentIndex);
            grandParent.add(parent);
            for(int childIndex =1; childIndex < 3; childIndex++) {
             child = new DefaultMutableTreeNode("[are the pains in the lower back?] " + childIndex +
                                         "." + childIndex);
              parent.add(child);
              child2 = new DefaultMutableTreeNode("patient over 60?" + childIndex +
                    "." + childIndex);
              child.add(child2);
            for(int grandChildIndex =1; grandChildIndex < 3; grandChildIndex++) {
               grandChild = new DefaultMutableTreeNode("[Does patient have bladder and/or bowel incontinence?] " + grandChildIndex +
                                            "." + grandChildIndex);
                 child.add(grandChild);
            for(int childIndex = 1; childIndex < 3; childIndex++) {
                child = new DefaultMutableTreeNode("[Has Patient suffered either: appitite/wieght loss/fever?]" + childIndex +
                                             "." + childIndex);
                child = new DefaultMutableTreeNode("[Has pain been 4-6wks leg pain? OR 3-6mths low-back pain?]" + childIndex +
                        "." + childIndex);
                  grandChild.add(child);
        tree = new JTree(root);
        //tree = new JTree(root2);
        tree.addTreeSelectionListener(this);
        content.add(new JScrollPane(tree), BorderLayout.CENTER);
        currentSelectionField = new JTextField("Current Selection: NONE");
        content.add(currentSelectionField, BorderLayout.SOUTH);
        setSize(400, 400);
        setVisible(true);
      public void valueChanged(TreeSelectionEvent event) {
        currentSelectionField.setText
          ("Current Selection: " +
           tree.getLastSelectedPathComponent().toString());
    }

    I'm not really sure what your problem is, for I don't see what you mean by "mirror". If it is you have but one root node, but wanted to have many instead, then you'd simply need to call setRootVisible(false); on the tree.
    As a sidenote, I don't think it's a really good UI for what you're doing, but after all, I haven't got the whole picture.
    Now, what is it you mean by: its not yielding the results I want ?

  • JTree problem

    I posted a simillar problem not long ago but didn't explain properly.
    The code below displays a JFrame with a JScrollPane containing a JTree with just a root node ("root").
    At the bottom of the frame is a button that when pressed re-initialises the JTree with no arguments (line 42). Hence once the button is clicked the JTree should have some elements in it (those default ones : colours, sports, food).
    However, the reinitialised JTree is not displayed. What's the problem?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    class Test extends JFrame implements ActionListener {
         private JScrollPane            treeScrollPane;
         private JTree                  tree;
         private DefaultMutableTreeNode root;
         private JButton                runButton;
         public Test() {
              super("Test");
              this.tree = new JTree(this.root = new DefaultMutableTreeNode("root"));
              this.treeScrollPane = new JScrollPane(new JTree());
              this.treeScrollPane.setBorder(BorderFactory.createCompoundBorder(
                   BorderFactory.createTitledBorder("Tree panel"),
                   BorderFactory.createEmptyBorder(5,5,5,5)));
              this.runButton = new JButton("click me");
              this.runButton.addActionListener(this);
              Container contentPane = getContentPane();
              contentPane.setLayout(new BorderLayout());
              contentPane.add(this.treeScrollPane, BorderLayout.CENTER);
              contentPane.add(this.runButton,      BorderLayout.SOUTH);
              this.setSize(300, 400);
              this.setLocationRelativeTo(null);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.setVisible(true);
         public void actionPerformed(ActionEvent e) {
              Object source = e.getSource();
              if (source == this.runButton) {
                   System.out.println("DEBUG : button clicked");
                   this.tree = new JTree();
                   this.tree.expandPath(new TreePath(this.tree.getModel().getRoot()));
         public static void main(String args[]) {
              try {
                   UIManager.setLookAndFeel(
                        UIManager.getSystemLookAndFeelClassName());
              } catch (Exception e) {
                   System.out.println(e.getMessage());
              new Test();
    }

    The problem is that the scrollpane is still displaying the first tree.
    To fix this, you'll need to add the following line to your actionPerformed method:
    treeScrollPane.setViewportView(tree);(I think you might be a litle confused by the difference between an object and a reference. The scrollpane holds a reference to the first tree you create. Then you create a new tree and assign it to your this.tree reference, but the scrollpane's reference is stil pointing to the first tree. If this explanation is all mumbled up it's because I haven't had my first cup of coffee yet :-)

  • JTree - problems with names of elements

    I have a Jtree thats populated with expandable elements. These elements are loaded on startup, but some of the elements don't get their full names, just i.e "dem..." instead of "demo3". WHen I expand the node, the full name appears, and remains.
    Anyone know what this could be?
    The problem is really often associated with nodes with names containing "m" ..

    By default the tree node renderer is JLabel.
    It look like you are not using pack() or validate().
    It depend also the layout manager you are using.
    In one word, it seems the JLabel has dimension too short.
    Can only show 3 to 4 char. that is why "demo3" show as "dem..."
    Try have some node name like "WWWWW", if you see "WW..." or "WWW..."
    Then that is the problem. ( Not as you thought: only "m" has problem )

  • JTree Problem again

    Deat 7rst,
    Sorry, I want to ask you about the same problem.
    if I want to display a difference components from difference node in JTree, how the code I must use?
    I already understand about the code that you give to me. But I still confuse if many nodes in JTree to perform difference panel with many components each of its. The components beside JTextField.
    Thanks

    I have used THE SEARCH BOX - can't find nothing about editable JList, there are only references for editable Trees and Tables.
    Do anybody have concrete idea (the best would be some code), or should I reconcile myself with the JTable solution?

  • JTree Problem - Need help

    Hi,
    I am using a JTree to which I have set my own TreeModel and TreeSelectionListener (overidden all the methods for both). Wehn I add a new node to the tree, the node appears but the text for the node does not.
    (e.g if the text is "ABCD", what appears is "AB..."). I called a tree.repaint(). It does not solve my problem.
    A tree.updateUI() does solve my problem, but it throws a NullPointerException on every selection in the tree. I am trying to refresh the tree in the selSelection() method of the selection model.
    Is there any other way?
    Thanks in advance,
    Achyuth

    Try adding this when you add a node. Don't have time to check it so not quite sure its what you're looking for but I remember having this prob before and I think this is what I did:
    EventListener[] listeners = ((DefaultTreeModel)tree.getModel()).getListeners(TreeModelListener.class);
    for (int i = 0; i < listeners.length; i++) {
              ((TreeModelListener)listeners).treeNodesChanged(new TreeModelEvent(this, new TreePath(node.getPath())));
    Alex

  • Any component as leaf for JTree problems

    hi,
    I'm trying to get arbitary components as leaves in a JTree and it looks like its very nearly there, but there are two (related?) problems.
    1) If you click around on the top 3 tree components then it gets stuck in a loop of rendering and causes a stack exception to be thrown.
    2) For the embedded JTree component, expanding its nodes doesn't update the parent tree
    both may be because current the row height is set at the wrong time (in the TreeCellRenderer)
    any help would be really appreciated!
    thanks,
    asjf
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    import java.util.*;
    public class ComponentTree
         public static void main(String args[])
              try{(new UIManager()).setLookAndFeel((new UIManager()).getSystemLookAndFeelClassName());}
              catch(Exception e){}
              DefaultMutableTreeNode c0 = new DefaultMutableTreeNode(new JButton("root"));
              DefaultMutableTreeNode c1 = new DefaultMutableTreeNode(new JButton("c1"));
              DefaultMutableTreeNode c2 = new DefaultMutableTreeNode(new JList(new Object [] {"A","B","C"}));
              DefaultMutableTreeNode c3 = new DefaultMutableTreeNode(new JTable(new Object [][] {{"Active","true"},{"User","root"}}, new Object [] {"Name","Value"}));
              DefaultMutableTreeNode c4 = new DefaultMutableTreeNode(new JTree());
              DefaultMutableTreeNode c5 = new DefaultMutableTreeNode(new JList(new Object [] {"D","E","F"}));
              DefaultMutableTreeNode c6 = new DefaultMutableTreeNode(new JCheckBox("Active",true));
              DefaultTreeModel dtm = new DefaultTreeModel(c0);
                   dtm.insertNodeInto(c6,c0,0);
                   dtm.insertNodeInto(c1,c0,0);
                   dtm.insertNodeInto(c2,c0,0);
                   dtm.insertNodeInto(c5,c2,0);
                   dtm.insertNodeInto(c3,c1,0);
                   dtm.insertNodeInto(c4,c3,0);
              JTree tree = new JTree(dtm);
                   tree.setEditable(true);
                   tree.setCellRenderer(new DefaultTreeCellRenderer()
                        public Component getTreeCellRendererComponent(     JTree tree,     Object value, boolean isSelected, boolean expanded, boolean leaf, int row, boolean hasFocus)
                             System.out.println("Render row "+row);
                             Component c = (Component) ((DefaultMutableTreeNode) value).getUserObject();
                             if(c instanceof JCheckBox)
                                  c.setBackground(UIManager.getColor("Tree.textBackground"));
                             tree.setRowHeight(c.getHeight());                    
                             return c;     
                   tree.setCellEditor(new DefaultTreeCellEditor(tree,(DefaultTreeCellRenderer)tree.getCellRenderer())
                        public boolean isCellEditable(EventObject evt){return true;}
                        public Component getTreeCellEditorComponent(     JTree tree,     Object value, boolean isSelected, boolean expanded, boolean leaf, int row)
                             return (Component) ((DefaultMutableTreeNode) value).getUserObject();
              JFrame frame = new JFrame("ComponentTree");
                   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frame.getContentPane().add(tree);     
                   frame.pack();
                   frame.show();
    }

    thanks!
    this seems an awful lot of code to get this working - it should be possible to have a single CellEditor/Renderer??
    also running the code - its very hard to select checkbox items, and the JLists seem to disable themselves when the main tree updates?
    its also not general to any Component (?) (although we probably only want JComponent) so we can't add a JTree as a leaf?
    I'm guessing there is a simpler way to get this working?

  • JTree: Problems updating the nodes size

    Hi,
    I'm trying to update the content of a JTree and I wonder how it
    really works, since the paint() method doesn't seem to call the
    renderer.
    My situation: Imagine a JPanel splited in two by a JSplitPane. In
    the left is the tree. Each node in the tree shows two panels, one
    aligned to the left, and another to the right. I need that the panel
    containing the two use all the available space in the left part of the
    Split panel.
    My solution: I pass the left JPanel to the tree renderer, so that
    it can get the width from it (inside the
    getTreeCellRendererComponent()) to build the return JPanel with the
    correct size. My logic is that since each time you move the JSplitPane
    the JTree paint() method is invoked the renderer can return the
    correct JPanel with the correct size that will be painted then in the
    screen.
    My problem: Doens't work. When I render the tree, the renderer is
    invoked, but it doesn't change its size (I can change the color based on the width, but not the node size). Only when I collapse & expand a node, it correctly takes into account the .setPreferredSize() and returns the JPanel with the correct size.
    The only way I found to update the tree involves to catch the
    JSplitPane event and call updateUI() in the tree, something that, I
    think, it's certainly not the correct way to do it.
    Any explanation of why this doesn't work would be really great. Any
    pointer to a web resource explaining in deep how Swing components work (specially the JTree) would be a godsend.
    Thanks,
    - Juancho

    My situation: Imagine a JPanel splited in two by a JSplitPane. Got it.
    In the left is the tree. In the left side of the JSplitPane is a JTree.
    Each node in the tree shows two panels,Maybe... on the right side of the JSplitPane are two Panels in which the data depends on which node is selected in the JTree???
    Maybe... you have a custom TreeCellRenderer which displays a pair of panels in place of the standard JLabel???
    one aligned to the left, and another to the right. To the left of what??? To the right of what???
    I need that the panel containing the two use all the available
    space in the left part of the Split panel.Panel containing the two what??? I thought the left part of the SplitPanel contained a JTree???

  • JTree problems (getting urgent)

    A screen prototype that I am writing uses a JTree and a JList.
    Whenever the JTree is Expanded or Colapsed, the list is updated so that is displays:
    myJTree.getPathForRow(i).getPathComponent(1);
    where i is the row of both the tree and the list.
    My problem is that the list is always one stage behind!
    ie my JTree is initialised(with root hidden):
    Colour
    Fruit
    Sport
    and the list box displays:
    Colour
    Fruit
    Sport
    if I expand Colour, the tree displays:
    Colour
    -Red
    -Green
    Fruit
    Sport
    and the list displays:
    Colour
    Fruit
    Sport
    then I expand Fruit, the tree displays:
    Colour
    -Red
    -Green
    Fruit
    -Apple
    Sport
    the list displays:
    Colour
    Colour
    Colour
    Fruit
    Sport
    etc. etc.
    why is this happening?
    and how can I change my code so that the list displays what the tree is displaying and not what the tree used to display!

    This is the update method:
    DefaultListModel model = new DefaultListModel();
    for(int i = 0; i<myJTree.getRowCount();++i) {
    model.addElement(myJTree.getPathForRow(i).getPathComponent(1));
    and the JTree expansion listener finds out which frame it is being called from before calling the update method on that frame.
    When you say, remove all the items from the list, do you mean remove the previous model?

  • Jclient - Jtree problem inserting new records

    I reviewed the component example of using a jtree and for display only it works fine but doesn't include any code to add new records. our example uses a polymorphic table called "levels", as:
    level1
    __| level2
    _____| level3
    inserting a record to the level1 vo works and redisplays in the jtree fine but inserts to level2 or level3 creates
    display issues and other tree issues. The data is recorded correctly and the tree displays correctly if you close the app and rerun it.
    We also attempted to correct this by setting
    vo.setAssociationConsistent(true) in each of the level table vos. this did not help.
    Is this a bug ? Can someone provide some example code if required to get this to display and insert correctly.

    Robert,
    I can't tell if the problem is a bug and it would require code reviews and test cases to be specific on that.
    I suggest contacting customer support with this issue so the problem gets documented, addressed and solved.
    See: metalink.oracle.com
    Frank

  • Jtree - Problem creating a very large one

    Hi,
    I need to create a multi-level JTree that is very large (aroung 600-650 nodes all in all). At present I am doing the same by creating DefaultMutableTreeNodes and adding them one by one to the tree. It takes a very long time to complete(obviously).
    Is there any way of doing this faster? The tree is being constructed from run-time data.
    Thanks in advance,
    Regards,
    Achyuth

    Two thoughts. First, I create 100's of nodes and it's pretty fast. It could be how you are creating/adding them. Make sure your code is not the bottleneck. If you are traversing the entire tree or some other odd way of doing it, it could be the problem. I only say that because I am able to create an object structre, parse XML as I create that structe and create all the nodes and its less than 1 second on a PIV 1.7Ghz system. Maybe on slower systems its a lot slower, but for me its up immediately.
    Another way, however, is to keep a Map of "paths" to child items in memory. As you build your object from whever, use a Map to keep path info. Now, add listeners to the tree for expand/collapse. Each time it is about to expand, build up the nodes and add them to the expanding node at that point. If it collapses, discard them. This does one of two things. First, for large trees, you aren't wasting tons of time building the tree at the start, and more so, its probably likely that all those nodes aren't going to be expanded/shown right away. Second, it conserves resources. If your tree MUST open in a fully epxanded state, well, then you may be out of luck. But I would much prefer epxanding and building the child nodes at that moment, rather than do the whole thing first.

  • Simple JTree problem

    Hi,
    I am new to swings .. so this might be a dumb problem for you UI experts.
    I have a JTree using a custom TreeRenderer. Now the getTreeCellRendererComponent() of the custom TreeRenderer is called every time the tree is clicked. I have some icons in the tree that I dynamically load / change in this method. I want the same thing to happen every second (without clicks).
    So, I wrote an inner thread, and the run method is like this:
              Thread refresher = new Thread() {
                   public void run() {
                        try {
                             Thread.sleep(1000);
                        } catch (InterruptedException e) {
                             e.printStackTrace();
    // What shall I call here? tree.repaint() ?
    The problem is that I don't know what do I need to call at the place where I've put the comment so that the getTreeCellRendererComponent() is called for all tree components just as it is called on clicks.

    It may have done the trick, but it's the wrong solution. As dkrukovsky said, you
    should be invoking nodeChanged() when you change a node, including
    the icon. That will handle the repaint for you, ensure internal consistency
    of the tree, and get rid of your totally unnecessary Thread.

  • Search Jtree Problem (Easy Duke dollars)

    Hi all,
    I know that in order to find a node is a tree I can use getNextMatch method given by JTree. However, the problem here is that I want to serach for a child node and I don't know how to... for example...
    Root
    - Child 1
    - Child 2
    - Child 3
    If I search for the root node I would simply do
    getNextMatch("R",0,Position.Bias.Forward);But what if I want to search for Child 1 or Child 3? What would be in my search string?

    Hi,
    To search for a node in a JTree, you may use the breadthFirstEnumeration() method of the DefaultMutableTreeNode and then iterate through that enumeration until the desired node is found or the node is not found.
    You need to have a reference to the Root of the tree as a DefaultMutableTreeNode where the seacrh will begin.
    Let's say that the desired node's data = desiredElement
    DefaultMutableTreeNode root = new DefaultMutableTreeNode(.....);
    java.util.Enumeration enum = root.breadthFirstEnumeration();
    while(enum.hasMoreElements())
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) enum.nextElement();
    if(node.getUserObject().equals(desiredElement))
    //you have found the node in the tree
    //you can get the parent using the getParent on this node as well
    //if you want the search path as well
    //if you reach here, the desired node is not in the tree
    mail me in case of problem : [email protected]

  • JTree problem displaying nodes

    I have created a GUI, in which part of it allows the user to view files in a selected folder in a JTree format.
    The tree only shows selected files with certain extensions (such as ".txt", ".doc", etc.. see code below)
    I'll try to show what it looks like, for example:
    - RootFolder
        - SomeOpenFolder
            - someFile
            - anotherFile
        + SomeClosedFolder
        - File_in_RootFolder
        - Another_file_in_RootFolder Anyhow, when I shipped it to my boss he occasionally cannot view the full file names..
    for example:
    - RootFolder
        - SomeOp....
            - some....
            - anothe...
        + SomeClo...
        - File_in_R...
        - Another_fil...I have the JTree inside a JScrollPane with horizontalScrollBarPolicy set to "AS_NEEDED"
    I have run several tests, with both LONG and SHORT names... and it all works just fine for me
    For example:
    - RootFolder
        - SomeOpenFolder
            - someFile
            - anotherFile_With_A_VERY_VERY_VERY_VERY_LOOOOOOOOOOOOOOOOOOOONG_NAME
        + SomeClosedFolder_With_A_VERY_VERY_VERY_VERY_LOOOONG_NAME
        - File_in_RootFolder
        - Another_file_in_RootFolder And i am able to scroll left&right to view the full name within the scroll panel.
    But for some reason, on my Bosses computer sometimes it has the full name,
    and other times it cuts the name short with "FolderNa..."
    Is anyone aware of why such a problem could happen?
    Here is my code setting up the tree.
    public void setMyTree(String myFolder)
    File rootFile = new File(myFolder);
            JTree targetTree = new JTree(TreeSetup(rootFile, InputIncludeFilter()));
            targetTree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
            targetTree.setCellRenderer(new TreeCellRenderer() {
                  public Component getTreeCellRendererComponent(JTree tree, Object value,
                                boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
                      JLabel label = new JLabel(value.toString());
                      TreePath p = tree.getPathForRow(row);
                      if(p != null){
                          File node = getInputFile(p);                    
                      if (selected) {
                             label.setOpaque(true);
                             label.setBackground(tree.getBackground().darker());
                          return label;
                  private File getInputFile(TreePath path) {
                      StringBuffer fName = new StringBuffer();
                        boolean isroot = true;
                        for (Object s : path.getPath()) {
                                  fName.append(s + File.separator);                          
                      return new File(getUserDomain()+File.separator +
                                 fName.toString().substring(0, fName.toString().length() - 1));
    }Any ideas? Do would it help to see my method "InputIncludeFilter()"

    DefaultTreeCellRenderer extends from JLabel, so whatever you are doing to the JLabel you create you can do to the DefaultTreeCellRenderer too.
    This would be more like it:
           targetTree.setCellRenderer(new DefaultTreeCellRenderer() {
                  public Component getTreeCellRendererComponent(JTree tree, Object value,
                                boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus)
                     super.getTreeCellRendererComponent(tree,value,selected,expanded,leaf,row,hasFocus);
                      TreePath p = tree.getPathForRow(row);
                      if(p != null){
                          File node = getInputFile(p);                    
                      if (selected) {
                             this.setOpaque(true);
                             this.setBackground(tree.getBackground().darker());
                          return this;
                  }

  • Redraw JTree problem

    I have a probram that use SAX to parse xml file and display as JTree.
    I have problem redraw the tree using following code:
    SAXTreeBuilder saxTree = null;
    DefaultMutableTreeNode top = new DefaultMutableTreeNode(myxmlFile);
    saxTree = new SAXTreeBuilder(top);
    try {
    SAXParser saxParser = new SAXParser();
    saxParser.setContentHandler(saxTree);
    saxParser.parse(new InputSource(new FileInputStream(myxmlFile)));
    } catch (Exception ex) {
    top.add(new DefaultMutableTreeNode(ex.getMessage()));
    JFrame frame = getFrame();
    JTree tree = new JTree(saxTree.getTree());
    JScrollPane scrollPane = new JScrollPane(tree);
    frame.getContentPane().add(ascrollPane, BorderLayout.CENTER);
    frame.setVisible(true);

    Swing related questions should be posted in the Swing forum.
    But there is no need to repost because you can simply read the JTree API and follow the link to the Swing tutorial for an example of how to build a tree.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

Maybe you are looking for