IT_Programming/Java

Java Swing Tree 예제

JJun ™ 2007. 2. 5. 01:01

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.tree.*;

class JTreeTest extends JFrame {
        JTree  xTree;
        JLabel xStatus;
        
        public JTreeTest() {
                super("JTree Demo");

                DefaultMutableTreeNode root, node;

                root = new DefaultMutableTreeNode("각국의 인사말");

                node = new DefaultMutableTreeNode("한국");
                node.add(new DefaultMutableTreeNode("안녕하슈~"));
                node.add(new DefaultMutableTreeNode("반갑심데이~~"));
                node.add(new DefaultMutableTreeNode("반갑당께요~"));
                root.add(node);

                node = new DefaultMutableTreeNode("미국");
                node.add(new DefaultMutableTreeNode("Hi~"));
                node.add(new DefaultMutableTreeNode("Hello~"));
                node.add(new DefaultMutableTreeNode("Nice to meet you~"));
                root.add(node);

                xTree = new JTree(root);
                xTree.addTreeSelectionListener(        new TreeSelectionListener()
                        {
                                public void valueChanged(TreeSelectionEvent e) {
                                        DefaultMutableTreeNode n = (DefaultMutableTreeNode)

                                                                                 (e.getPath().getLastPathComponent());
                                        xStatus.setText((String)n.getUserObject());
                                }
                        }
                );
                xTree.expandRow(2);

                getContentPane().setLayout(new BorderLayout());
                getContentPane().add(new JScrollPane(xTree), "Center");

                xStatus = new JLabel("없슴");
                xStatus.setBorder(new TitledBorder("선택된항목"));
                getContentPane().add(xStatus, "South");
        }

        public static void main(String[] args) {
                JTreeTest f = new JTreeTest();
                f.addWindowListener(new WindowAdapter()
                        {
                                public void windowClosing(WindowEvent e){
                                        System.exit(0);
                                }
                        }
                );
                f.pack();
                f.setSize(300, 200);
                f.setVisible(true);
        
        }
}