Results 1 to 20 of 20
Like Tree1Likes
  • 1 Post By Fubarable

Thread: Call cardlayout with jtree node

  1. #1
    Deckon is offline Member
    Join Date
    Jan 2013
    Posts
    10
    Rep Power
    0

    Default Call cardlayout with jtree node

    I have a simple JFrame with a JTree and several JPanels in a CardLayout, I try to do is open a specific panel with some specific node.
    This is my code:
    Java Code:
    private void jTree2ValueChanged(javax.swing.event.TreeSelectionEvent evt) {
         DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) jTree2
         .getLastSelectedPathComponent();
        String selectedNodeName = selectedNode.toString();
        if (selectedNode.isRoot()) {
    
            System.out.println("Root node");
    
        }
        else if(selectedNode.isLeaf()){
            CardLayout cl= (CardLayout)(jPanel1.getLayout());
            cl.next(jPanel1);
    
        }
    I have the JTree with only two nodes: root, One, Two.
    When I click on the node "One" show me the panel, the same happens when I click on the third node "Two". But the problem is that the root node also works, for example: Node "One" shows the panel A and node "Two" shows the panel B, when I click on the root node functions change.

    I mean the root node shows the panel A and node "one" shows the panel B.

    How I can fix this? Any way to disable the root node click?

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

    Default Re: Call cardlayout with jtree node

    To get better help sooner, post a SSCCE (Short, Self Contained, Correct (Compilable), Example) that demonstrates the problem.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  3. #3
    Deckon is offline Member
    Join Date
    Jan 2013
    Posts
    10
    Rep Power
    0

    Default Re: Call cardlayout with jtree node

    Thanks for responding, with the entire project is enough?
    It really is very small, a simple JFrame with JTree and CardLayout.
    As I said before, the root node changes the order of the panels, I try to do is that the root node has no role, just like that other nodes can open the panel I want.

    This is the project:
    http://ompldr.org/vZ3l6MQ/Example.rar

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

    Default Re: Call cardlayout with jtree node

    Quote Originally Posted by Deckon View Post
    Thanks for responding, with the entire project is enough?
    It really is very small, a simple JFrame with JTree and CardLayout.
    As I said before, the root node changes the order of the panels, I try to do is that the root node has no role, just like that other nodes can open the panel I want.

    This is the project:
    http://ompldr.org/vZ3l6MQ/Example.rar
    If it's small enough to be posted here and not take up more than a screen or a screen and a half at most, then please do so -- post it here. If it's too large for that, then it's too large to ask volunteers to go through.
    DarrylBurke likes this.

  5. #5
    Deckon is offline Member
    Join Date
    Jan 2013
    Posts
    10
    Rep Power
    0

    Default Re: Call cardlayout with jtree node

    ok I understand, but I can not upload the project here, I do not see any option for uploading.
    The attachments option does not work, I get a blank window.
    Last edited by Deckon; 01-07-2013 at 04:58 AM.

  6. #6
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

    Default Re: Call cardlayout with jtree node

    You don't need to upload anything. Post an SSCCE.

    Guide For New Members
    BB Code List - Java Programming Forum - Learn Java Programming

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  7. #7
    Deckon is offline Member
    Join Date
    Jan 2013
    Posts
    10
    Rep Power
    0

    Default Re: Call cardlayout with jtree node

    I really do not understand what you want to do, this is the code I have, automatically add the CardLayout, the JPanel and JTree, and the value changed event of JTree code I have that I put up.
    Java Code:
                        
    
        private void jTree2ValueChanged(javax.swing.event.TreeSelectionEvent evt) {                                    
            
            DefaultMutableTreeNode Nodo = (DefaultMutableTreeNode) jTree2
            .getLastSelectedPathComponent();
            String NombreNodo = Nodo.toString();
            if (Nodo.isRoot()) {
               Nodo.getLevel();
               System.out.println(Nodo);  
            }
            else 
                
              if(Nodo.isLeaf()){  
               CardLayout cl= (CardLayout)(jPanel1.getLayout());
               cl.next(jPanel1);
    
            }

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

    Default Re: Call cardlayout with jtree node

    Quote Originally Posted by Deckon View Post
    I really do not understand what you want to do,...
    It's all well explained in the SSCCE that Darryl gave you in one of his earlier posts. Please read the link as it should make things pretty clear.

    this is the code I have, automatically add the CardLayout, the JPanel and JTree, and the value changed event of JTree code I have that I put up.
    Java Code:
                        
    
        private void jTree2ValueChanged(javax.swing.event.TreeSelectionEvent evt) {                                    
            
            DefaultMutableTreeNode Nodo = (DefaultMutableTreeNode) jTree2
            .getLastSelectedPathComponent();
            String NombreNodo = Nodo.toString();
            if (Nodo.isRoot()) {
               Nodo.getLevel();
               System.out.println(Nodo);  
            }
            else 
                
              if(Nodo.isLeaf()){  
               CardLayout cl= (CardLayout)(jPanel1.getLayout());
               cl.next(jPanel1);
    
            }
    Not sure I can do much with this code tid-bit.

  9. #9
    Deckon is offline Member
    Join Date
    Jan 2013
    Posts
    10
    Rep Power
    0

    Default Re: Call cardlayout with jtree node

    this?
    Java Code:
    import java.awt.CardLayout;
    import javax.swing.JTree;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreePath;
    
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    /**
     *
     * @author Admin
     */
    public class Form extends javax.swing.JFrame {
    
        /**
         * Creates new form Form
         */
        public Form() {
            initComponents();
            //jLabel1.setVisible(false);
        }
    
        /**
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
    
            jPanel1 = new javax.swing.JPanel();
            jPanel3 = new javax.swing.JPanel();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            jButton3 = new javax.swing.JButton();
            jRadioButton1 = new javax.swing.JRadioButton();
            jComboBox1 = new javax.swing.JComboBox();
            jPanel4 = new javax.swing.JPanel();
            jScrollPane2 = new javax.swing.JScrollPane();
            jTable1 = new javax.swing.JTable();
            jScrollPane3 = new javax.swing.JScrollPane();
            jTree2 = new javax.swing.JTree();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            jPanel1.setLayout(new java.awt.CardLayout());
    
            jButton1.setText("jButton1");
    
            jButton2.setText("jButton2");
    
            jButton3.setText("jButton3");
    
            jRadioButton1.setText("jRadioButton1");
    
            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
    
            javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
            jPanel3.setLayout(jPanel3Layout);
            jPanel3Layout.setHorizontalGroup(
                jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel3Layout.createSequentialGroup()
                    .addGap(40, 40, 40)
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel3Layout.createSequentialGroup()
                            .addComponent(jRadioButton1)
                            .addGap(18, 18, 18)
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel3Layout.createSequentialGroup()
                            .addComponent(jButton1)
                            .addGap(27, 27, 27)
                            .addComponent(jButton2)
                            .addGap(32, 32, 32)
                            .addComponent(jButton3)))
                    .addContainerGap(116, Short.MAX_VALUE))
            );
            jPanel3Layout.setVerticalGroup(
                jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel3Layout.createSequentialGroup()
                    .addGap(74, 74, 74)
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton1)
                        .addComponent(jButton2)
                        .addComponent(jButton3))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jRadioButton1)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(239, Short.MAX_VALUE))
            );
    
            jPanel1.add(jPanel3, "card3");
    
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                },
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
                }
            ));
            jScrollPane2.setViewportView(jTable1);
    
            javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
            jPanel4.setLayout(jPanel4Layout);
            jPanel4Layout.setHorizontalGroup(
                jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE)
            );
            jPanel4Layout.setVerticalGroup(
                jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel4Layout.createSequentialGroup()
                    .addGap(41, 41, 41)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(147, Short.MAX_VALUE))
            );
    
            jPanel1.add(jPanel4, "card4");
    
            javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root");
            javax.swing.tree.DefaultMutableTreeNode treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Uno");
            treeNode1.add(treeNode2);
            treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Dos");
            treeNode1.add(treeNode2);
            jTree2.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
            jTree2.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    jTree2MouseClicked(evt);
                }
            });
            jTree2.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
                public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                    jTree2ValueChanged(evt);
                }
            });
            jScrollPane3.setViewportView(jTree2);
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane3)
            );
    
            pack();
        }// </editor-fold>                        
    
        private void jTree2ValueChanged(javax.swing.event.TreeSelectionEvent evt) {                                    
            
            DefaultMutableTreeNode Nodo = (DefaultMutableTreeNode) jTree2
            .getLastSelectedPathComponent();
            String NombreNodo = Nodo.toString();
            if (Nodo.isRoot()) {
               Nodo.getLevel();
               System.out.println(Nodo);  
            }
            else 
                
              if(Nodo.isLeaf()){  
               CardLayout cl= (CardLayout)(jPanel1.getLayout());
               cl.next(jPanel1);
               Nodo.getPreviousLeaf();
    
            }
           
            
        }                                   
    
        private void jTree2MouseClicked(java.awt.event.MouseEvent evt) {                                    
            // TODO add your handling code here:
        }                                   
    
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
    
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Form().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JButton jButton3;
        private javax.swing.JComboBox jComboBox1;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JPanel jPanel3;
        private javax.swing.JPanel jPanel4;
        private javax.swing.JRadioButton jRadioButton1;
        private javax.swing.JScrollPane jScrollPane2;
        private javax.swing.JScrollPane jScrollPane3;
        private javax.swing.JTable jTable1;
        private javax.swing.JTree jTree2;
        // End of variables declaration                   
    }
    I add components automatically..

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

    Default Re: Call cardlayout with jtree node

    No, an SSCCE would be much shorter and without code not necessary for functioning or to display the problem. It would certainly not have the NetBeans generated junk. Something more on the order of this:

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    
    @SuppressWarnings("serial")
    public class Form2 extends JPanel {
       private static final int PREF_W = 500;
       private static final int PREF_H = 350;
       private JTree jTree = new JTree();
       private CardLayout cardLayout = new CardLayout();
       private JPanel cardHolderPanel = new JPanel(cardLayout);
    
       public Form2() {
          DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("root");
          for (NodeConstants nodeConst : NodeConstants.values()) {
             rootNode.add(new DefaultMutableTreeNode(nodeConst));
             cardHolderPanel.add(new JLabel(nodeConst.toString(), SwingConstants.CENTER), 
                   nodeConst.toString());
          }
          jTree.setModel(new DefaultTreeModel(rootNode));
          jTree.addTreeSelectionListener(new TreeSelectionListener() {
             
             @Override
             public void valueChanged(TreeSelectionEvent tsEvt) {
                TreePath treePath = tsEvt.getNewLeadSelectionPath();
                Object[] pathArray = treePath.getPath();
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) pathArray[pathArray.length - 1];
                if (!node.isRoot()) {
                   cardLayout.show(cardHolderPanel, node.toString());
                }
                System.out.println(node);
             }
          });
               
          setLayout(new BorderLayout());
          add(new JScrollPane(jTree), BorderLayout.WEST);
          add(cardHolderPanel, BorderLayout.CENTER);
       }
       
       @Override
       public Dimension getPreferredSize() {
          return new Dimension(PREF_W, PREF_H);
       }
    
       private static void createAndShowGui() {
          Form2 mainPanel = new Form2();
    
          JFrame frame = new JFrame("Form2");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    
    enum NodeConstants {
       UNO("Uno"), DOS("Dos"), TRES("Tres"), QUATRO("Quatro"), CINCO("Cinco");
       private String name;
    
       private NodeConstants(String name) {
          this.name = name;
       }
       
       @Override
       public String toString() {
          return name;
       }
    }
    So how is your code or mine not working right?

  11. #11
    Deckon is offline Member
    Join Date
    Jan 2013
    Posts
    10
    Rep Power
    0

    Default Re: Call cardlayout with jtree node

    In your code when you click on any node the name printed on the panel, I try to call another japanel, for now I have two JPanel, each has different components such as buttons, labels, tables, etc..

    I try to call a specific JPanel with any JTree nodes, eg
    Node A call to panel B, the node named C call the panel called D.
    Obviously my code is wrong, to be more accurate this part:
    Java Code:
    CardLayout cl= (CardLayout)(jPanel1.getLayout());
              cl.next(jPanel1);
    Using buttons can be something like:
    Java Code:
    CardLayout cl= (CardLayout)(jPanel1.getLayout());
    cl.show(jPanel1, "card3");
    and if it works, call specified JPanel, but I really want to use the JTree.

    Always call the next panel, but also the root node calls the next panel and that's what I would not, as might specify that node X will open JPanel?

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

    Default Re: Call cardlayout with jtree node

    Quote Originally Posted by Deckon View Post
    In your code when you click on any node the name printed on the panel, I try to call another japanel, for now I have two JPanel, each has different components such as buttons, labels, tables, etc..

    I try to call a specific JPanel with any JTree nodes, eg
    Node A call to panel B, the node named C call the panel called D.
    Obviously my code is wrong, to be more accurate this part:
    Java Code:
    CardLayout cl= (CardLayout)(jPanel1.getLayout());
              cl.next(jPanel1);
    Using buttons can be something like:
    Java Code:
    CardLayout cl= (CardLayout)(jPanel1.getLayout());
    cl.show(jPanel1, "card3");
    and if it works, call specified JPanel, but I really want to use the JTree.

    Always call the next panel, but also the root node calls the next panel and that's what I would not, as might specify that node X will open JPanel?
    You need to use CardLayout correctly. Don't get your "card" your JPanel by calling next(...) on the CardLayout. Instead use CardLayout's show(String key) method, and have the key String be somehow linked to your JTree node (see my example above). But also, do you see how smaller code is easier for us to go through? When posting here, please avoid the NetBeans crap code as it is not needed and only detracts.

  13. #13
    Deckon is offline Member
    Join Date
    Jan 2013
    Posts
    10
    Rep Power
    0

    Default Re: Call cardlayout with jtree node

    Now print the path of the selected node:
    Java Code:
      if(!Nodo.isRoot())  {
                     CardLayout cl= (CardLayout)(jPanel1.getLayout());
                     cl.show(jPanel1, "card3"+evt.getPath());
                     System.out.println(evt.getPath());
                }
    Output:
    [root, Uno]
    [root, Dos]
    But not link the node to JPanel I want to open in your code here as I understand you link the node:
    Java Code:
    public void valueChanged(TreeSelectionEvent tsEvt) {
                TreePath treePath = tsEvt.getNewLeadSelectionPath();
                Object[] pathArray = treePath.getPath();
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) pathArray[pathArray.length - 1];
                if (!node.isRoot()) {
                   cardLayout.show(cardHolderPanel, node.toString());
                }
                System.out.println(node);
             }
          });
    When the selection of the node changes, then prints the name of the node the JPanel..

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

  15. #15
    Deckon is offline Member
    Join Date
    Jan 2013
    Posts
    10
    Rep Power
    0

    Default Re: Call cardlayout with jtree node

    how I can link to JTree nodes each JPanel?

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

    Default Re: Call cardlayout with jtree node

    I would create a class with the specific purpose of tying a node to a JPanel. I would use this class to allow us to add all JPanels and node Strings. For instance the class could accept in its constructor the JTree, the CardLayout, and the CardLayout using JPanel. You could give this class a method that accepts a String for the node's String and a JPanel or more generally a JComponent for the "card" component added to the cardlayout using JPanel. This class would have the tree selection listener inside of it and would be responsible for telling the CardLayout to show the panel.

    For instance, something like this:

    Java Code:
    class TieNodesWithCards {
       private static final String INITIAL_PANEL = "initial panel";
       private JTree jTree;
       private CardLayout cardlayout;
       private JPanel cardHolderPanel;
    
       public TieNodesWithCards(JTree jTree, final CardLayout cardlayout,
             final JPanel cardHolderPanel) {
          this.jTree = jTree;
          this.cardlayout = cardlayout;
          this.cardHolderPanel = cardHolderPanel;
          cardHolderPanel.setLayout(cardlayout);
          jTree.addTreeSelectionListener(new MyTreeSelectionListener());
          
          JPanel initialPanel = new JPanel();
          cardHolderPanel.add(initialPanel, INITIAL_PANEL);
       }
    
       public void addNodeTextAndComponent(String nodeText, JComponent component) {
          DefaultMutableTreeNode node = new DefaultMutableTreeNode(nodeText);
    
          DefaultTreeModel model = (DefaultTreeModel) jTree.getModel();
          DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
          System.out.println("root: " + root);
          root.add(node);
          System.out.println(node); // !! delete
          cardHolderPanel.add(component, node.toString());
          
          cardlayout.show(cardHolderPanel, INITIAL_PANEL);
       }
    
       private class MyTreeSelectionListener implements TreeSelectionListener {
          public void valueChanged(TreeSelectionEvent tsEvt) {
             TreePath treePath = tsEvt.getNewLeadSelectionPath();
             Object[] pathArray = treePath.getPath();
             DefaultMutableTreeNode node = (DefaultMutableTreeNode) pathArray[pathArray.length - 1];
             if (!node.isRoot()) {
                cardlayout.show(cardHolderPanel, node.toString());
             }
             System.out.println(node);
          }
       }
    
    }
    A working example could look like so:

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.CardLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.GradientPaint;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.RenderingHints;
    
    import javax.swing.*;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.*;
    
    public class TieNodesWithCardsTest {
       private static void createAndShowGui() {
          Form2 mainPanel = new Form2();
    
          JFrame frame = new JFrame("Form2");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    
    @SuppressWarnings("serial")
    class Form2 extends JPanel {
       private static final int PREF_W = 500;
       private static final int PREF_H = 350;
       private JTree jTree = new JTree();
       private CardLayout cardLayout = new CardLayout();
       private JPanel cardHolderPanel = new JPanel(cardLayout);
       private TieNodesWithCards tieNodesWithCards = new TieNodesWithCards(jTree,
             cardLayout, cardHolderPanel);
    
       public Form2() {
          DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("root");
    
          jTree.setModel(new DefaultTreeModel(rootNode));
    
          setLayout(new BorderLayout());
          add(new JScrollPane(jTree), BorderLayout.WEST);
          add(cardHolderPanel, BorderLayout.CENTER);
    
          tieNodesWithCards.addNodeTextAndComponent("Data Entry Panel",
                createDataEntryPanel());
          tieNodesWithCards.addNodeTextAndComponent("Color Panel",
                createColorPanel());
          TreePath treePath = new TreePath(rootNode);
          jTree.expandPath(treePath);
       }
    
       private JComponent createColorPanel() {
          JPanel colorPanel = new JPanel() {
             @Override
             protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D) g;
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                      RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setPaint(new GradientPaint(0, 0, Color.red, 30, 30, Color.blue,
                      true));
                g2.fillOval(0, 0, getWidth() * 2, getHeight() * 2);
             }
          };
          return colorPanel;
       }
    
       private JComponent createDataEntryPanel() {
          JLabel titleLabel = new JLabel("Data Entry", SwingConstants.CENTER);
          titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 20));
    
          String[] dataFields = { "Last Name:", "First Name:", "Date of Birth:",
                "ID:" };
          JPanel fieldPanel = new JPanel(new GridBagLayout());
          for (int row = 0; row < dataFields.length; row++) {
             JLabel label = new JLabel(dataFields[row]);
             JTextField textfield = new JTextField(10);
    
             GridBagConstraints gbc = new GridBagConstraints(0, row, 1, 1, 1.0,
                   1.0, GridBagConstraints.WEST, GridBagConstraints.BOTH,
                   new Insets(5, 5, 5, 15), 0, 0);
             fieldPanel.add(label, gbc);
             gbc = new GridBagConstraints(1, row, 1, 1, 1.0,
                   1.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL,
                   new Insets(5, 15, 5, 5), 0, 0);
             fieldPanel.add(textfield, gbc);
          }
    
          JPanel fieldPanelWrapper = new JPanel(new BorderLayout());
          fieldPanelWrapper.add(fieldPanel, BorderLayout.NORTH);
    
          JPanel dataEntryPanel = new JPanel(new BorderLayout(10, 10));
          dataEntryPanel.add(titleLabel, BorderLayout.NORTH);
          dataEntryPanel.add(fieldPanelWrapper, BorderLayout.CENTER);
          return dataEntryPanel;
       }
    
       @Override
       public Dimension getPreferredSize() {
          return new Dimension(PREF_W, PREF_H);
       }
    }
    
    class TieNodesWithCards {
       private static final String INITIAL_PANEL = "initial panel";
       private JTree jTree;
       private CardLayout cardlayout;
       private JPanel cardHolderPanel;
    
       public TieNodesWithCards(JTree jTree, final CardLayout cardlayout,
             final JPanel cardHolderPanel) {
          this.jTree = jTree;
          this.cardlayout = cardlayout;
          this.cardHolderPanel = cardHolderPanel;
          cardHolderPanel.setLayout(cardlayout);
          jTree.addTreeSelectionListener(new MyTreeSelectionListener());
          
          JPanel initialPanel = new JPanel();
          cardHolderPanel.add(initialPanel, INITIAL_PANEL);
       }
    
       public void addNodeTextAndComponent(String nodeText, JComponent component) {
          DefaultMutableTreeNode node = new DefaultMutableTreeNode(nodeText);
    
          DefaultTreeModel model = (DefaultTreeModel) jTree.getModel();
          DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
          System.out.println("root: " + root);
          root.add(node);
          System.out.println(node); // !! delete
          cardHolderPanel.add(component, node.toString());
          
          cardlayout.show(cardHolderPanel, INITIAL_PANEL);
       }
    
       private class MyTreeSelectionListener implements TreeSelectionListener {
          public void valueChanged(TreeSelectionEvent tsEvt) {
             TreePath treePath = tsEvt.getNewLeadSelectionPath();
             Object[] pathArray = treePath.getPath();
             DefaultMutableTreeNode node = (DefaultMutableTreeNode) pathArray[pathArray.length - 1];
             if (!node.isRoot()) {
                cardlayout.show(cardHolderPanel, node.toString());
             }
             System.out.println(node);
          }
       }
    
    }

  17. #17
    Deckon is offline Member
    Join Date
    Jan 2013
    Posts
    10
    Rep Power
    0

    Default Re: Call cardlayout with jtree node

    Ok I get it, but then without using a class is not possible?
    My idea will not use a class, if not from the same code and JFrame events, it would not be possible to do?

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

    Default Re: Call cardlayout with jtree node

    Quote Originally Posted by Deckon View Post
    Ok I get it, but then without using a class is not possible?
    My idea will not use a class, if not from the same code and JFrame events, it would not be possible to do?
    Please clarify including why you absolutely can't use a created class. But regardless of the specifics of your problem, the general logistics of my suggested solution still can be used. You just have to code it.

  19. #19
    Deckon is offline Member
    Join Date
    Jan 2013
    Posts
    10
    Rep Power
    0

    Default Re: Call cardlayout with jtree node

    I really am a newbie in programming, I have only been a few days starting with Java programming.
    I understand some of your code, and see where you add method to link the panel to the node.

    But for now I want to do it from the code of JFrame, using their own events.
    Thanks for helping.

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

    Default Re: Call cardlayout with jtree node

    Quote Originally Posted by Deckon View Post
    I really am a newbie in programming, I have only been a few days starting with Java programming.
    I understand some of your code, and see where you add method to link the panel to the node.

    But for now I want to do it from the code of JFrame, using their own events.
    Thanks for helping.
    OK, then give it a go. If you get stuck with it, show us your latest iteration and let's see if we can help.

Similar Threads

  1. action to a node in a jtree
    By sniffer139 in forum AWT / Swing
    Replies: 4
    Last Post: 08-29-2014, 04:51 PM
  2. How to change JTree's node icon manually?
    By LeonLanford in forum AWT / Swing
    Replies: 3
    Last Post: 09-29-2010, 04:14 PM
  3. Multiple components as one node in JTree
    By Amnuriak in forum AWT / Swing
    Replies: 8
    Last Post: 11-04-2009, 03:47 PM
  4. How to add JCheckbox as a node in JTree
    By shajuantony in forum New To Java
    Replies: 0
    Last Post: 04-09-2009, 08:19 AM
  5. Node selection in jtree
    By Preethi in forum AWT / Swing
    Replies: 4
    Last Post: 06-20-2008, 12:25 AM

Tags for this Thread

Posting Permissions

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