简略的说就是节点(DefaultMutableTreeNodes)加内容,内容再加内容,(前内容)便子节点。
package test;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.GridLayout;
import javax.swing.JTextArea;
public class NewTest {
private DefaultMutableTreeNode root = new DefaultMutableTreeNode("学校管理");
private DefaultMutableTreeNode t = new DefaultMutableTreeNode("教师");
private DefaultMutableTreeNode s = new DefaultMutableTreeNode("学生");
private DefaultMutableTreeNode t1 = new DefaultMutableTreeNode("孔子");
private DefaultMutableTreeNode t2 = new DefaultMutableTreeNode("孟子");
private DefaultMutableTreeNode s1 = new DefaultMutableTreeNode("子路");
private DefaultMutableTreeNode s2 = new DefaultMutableTreeNode("子游");
private DefaultMutableTreeNode s3 = new DefaultMutableTreeNode("子渊");
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NewTest window = new NewTest();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public NewTest() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 543, 405);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBounds(0, 0, 180, 358);
panel.add(panel_1);
panel_1.setLayout(null);
JPanel panel_2 = new JPanel();
panel_2.setBounds(179, 0, 346, 358);
panel.add(panel_2);
panel_2.setLayout(new GridLayout(1, 0, 0, 0));
JTextArea textArea = new JTextArea();
panel_2.add(textArea);
JTree tree = new JTree(root);
root.add(s);
root.add(t);
s.add(s1);
s.add(s2);
s.add(s3);
t.add(t1);
t.add(t2);
tree.setBounds(0, 0, 180, 358);
panel_1.add(tree);
tree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
// TODO Auto-generated method stub
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
if(node.isLeaf()) {
textArea.setText(node.getUserObject().toString());
}
}
});
}
}
效果显示: