如题:
设计图形界面类:
import java.awt.Container; import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; public class t3 extends JFrame { //三个控件(jtree也继承自组件Jcomponent) //窗口容器包含面板,面板包含滚动面板;滚动面板包含树。 JPanel jp; JScrollPane jsp; JTree tree; t3() { //设置标题 setTitle("JFrameTest"); //设置窗口大小、位置(左边距、上边距、宽、高) setBounds(400, 400, 400, 400); DefaultMutableTreeNode root=new DefaultMutableTreeNode("School"); DefaultMutableTreeNode c1=new DefaultMutableTreeNode("1班"); DefaultMutableTreeNode c2=new DefaultMutableTreeNode("2班"); DefaultMutableTreeNode p1=new DefaultMutableTreeNode("张三"); DefaultMutableTreeNode p2=new DefaultMutableTreeNode("李四"); DefaultMutableTreeNode p3=new DefaultMutableTreeNode("王五"); DefaultMutableTreeNode p4=new DefaultMutableTreeNode("赵六"); root.add(c1); root.add(c2); c1.add(p1); c1.add(p2); c2.add(p3); c2.add(p4); tree=new JTree(root); jsp=new JScrollPane(tree); jsp.setPreferredSize(new Dimension(200,200)); jp=new JPanel(); jp.add(jsp); // Container con=getContentPane(); con.add(jp); } }
主程序:
import javax.swing.JFrame; public class c1 { public static void main(String[] args) { t3 t=new t3(); //相当于show t.setVisible(true); //关闭即退出,可避免调试的时候main不退出,一般应保留 t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
运行效果: