jTree节点选择

时间:2015-01-24 17:01:50

标签: java swing jtree cardlayout

我有JFramejTree和displayPanel,还有FirstPanel和SecondPanel。点击jTree每个jPanels都会选择节点。

这是代码:

package demo;

import java.awt.CardLayout;
import java.awt.event.MouseEvent;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

public class Main extends javax.swing.JFrame {

    /**
     * Creates new form Main
     */
    public Main() {
        initComponents();
    }

    /**
     * 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() {

        treePanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        displayPanel = new javax.swing.JPanel();
        firstPanel = new demo.FirstPanel();
        secondPanel = new demo.SecondPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("Main");
        javax.swing.tree.DefaultMutableTreeNode treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Unit");
        javax.swing.tree.DefaultMutableTreeNode treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("time");
        treeNode2.add(treeNode3);
        treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("velocity");
        treeNode2.add(treeNode3);
        treeNode1.add(treeNode2);
        jTree1.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                jTree1ValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jTree1);

        treePanel.add(jScrollPane1);

        getContentPane().add(treePanel, java.awt.BorderLayout.WEST);

        displayPanel.setLayout(new java.awt.CardLayout());
        displayPanel.add(firstPanel, "first");
        displayPanel.add(secondPanel, "second");

        getContentPane().add(displayPanel, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>                        

    private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt) {                                    
         String node = evt.getNewLeadSelectionPath().getLastPathComponent().toString();
         if (node == null)
         return;
    if( node.equals("time") ) {
        displayPanel.add(firstPanel);
    } else if( node.equals("velocity") ) {
       displayPanel.add(secondPanel);
    }

    }                                   

    /**
     * @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(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.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 Main().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JPanel displayPanel;
    private demo.FirstPanel firstPanel;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTree jTree1;
    private demo.SecondPanel secondPanel;
    private javax.swing.JPanel treePanel;
    // End of variables declaration                   
}

问题在于:

private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt) {                                    
         String node = evt.getNewLeadSelectionPath().getLastPathComponent().toString();
         if (node == null)
         return;
    **if( node.equals("time") ) {
        displayPanel.add(firstPanel);
    } else if( node.equals("velocity") ) {
       displayPanel.add(secondPanel);**
    }

当我点击时间节点时,它会显示 secondPanel ,点击速度节点时会显示 firstPanel 。我不知道如何切换它们。 问题是:如何使时间节点显示 firstPanel 速度节点显示 secondPanel

提前谢谢。

1 个答案:

答案 0 :(得分:1)

问题在于:

displayPanel.add(firstPanel);
...
displayPanel.add(secondPanel);

您正尝试将组件添加到已显示的容器中,组件的层次结构为invalidated。在动态添加/删除组件时,您需要重新验证组件层次结构:

displayPanel.add(firstPanel);
displayPanel.revalidate(); // calls the layout manager
displayPanel.repaint(); // repaints the component

然而,恕我直言,这是CardLayout的一个很好的用例(链接到教程)。我建议你采用这种方法:

  1. cardPanel CardLayout放置在您希望面板显示的区域。
  2. 使用适当的约束(即:firstPanelsecondPanel将所有面板(cardPaneltime,...)添加到此velocity。< / LI>
  3. 在树选择更改时,使用CardLayout方法show(cardPanel, constraint)切换面板,其中constraint是用于将面板添加到cardPanel的约束。