怎么根据JSplitPane左边的内容,比如JTree,在右边动态显示不同的JPanel,JPanel包含JLabel 和JTextField.
我用JSplitPane splitPane=new JSplitPane(JSplitPane.
HORIZONTAL_SPLIT,tree,rightpanel);
rightpanel,怎么根据需要动态的改变成panel1,panel2,panel3?

解决方案 »

  1.   

    import java.awt.BorderLayout;
    import java.util.HashMap;
    import java.util.Map;import javax.swing.*;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.TreePath;public class DynamicUITest {
        public static void main(String[] args) {
            JTree tree = new JTree();
            JScrollPane sp = new JScrollPane(tree);
            
            final JPanel rightPanel = new JPanel(new BorderLayout());
            JSplitPane splitPane = new JSplitPane(
                    JSplitPane.HORIZONTAL_SPLIT, sp, rightPanel);
            splitPane.setDividerLocation(150);
            
            final Map nodeCompMap = new HashMap();        
            tree.addTreeSelectionListener(new TreeSelectionListener() {
                public void valueChanged(TreeSelectionEvent e) {
                    TreePath path = e.getPath();
                    if (path != null) {
                        String nodeName = path.getLastPathComponent().toString();
                        JComponent comp = (JComponent) nodeCompMap.get(nodeName);
                        if (comp == null) {
                            comp = createComponent(nodeName);
                            nodeCompMap.put(nodeName, comp);
                        }
                        rightPanel.removeAll();
                        rightPanel.add(comp, BorderLayout.CENTER);
                        rightPanel.revalidate();
                        rightPanel.repaint();
                    }
                }
            });
            
            JFrame f = new JFrame("DynamicUITest");
            f.getContentPane().add(splitPane, BorderLayout.CENTER);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize(800, 600);
            f.setLocationRelativeTo(null);
            f.show();
        }
        
        private static JComponent createComponent(String nodeName) {
            JPanel p = new JPanel();
            p.add(new JLabel(nodeName));
            p.add(new JTextField(nodeName));
            return p;
        }}