首页 > 代码库 > GUI树组件,表格
GUI树组件,表格
树组件首先要new一个JTree,再加结点,然后添加到 JScrollPane
JTree tree1=new JTree(); //.......添加节点 add(new ScrollPane(tree1)
添加节点
DefaultMutableTreeNode root=new DefaultMutableTreeNode("dongxi")//后面的是备注 DefaultMutableTreeNode root=new DefaultMutableTreeNode(new Good("aa",11));//还可以作为叶子new 对象
添加监视器(由树来添加
addTreeSelectionListener(TreeSelectionListener listener)
TreeSelectionListener接口的方法
public void valueChanged(TreeSelectionEvent e)
在上面的接口方法中,返回树的结点,再返回结点中的对象
DefaultMutableTreeNode node1=(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();//只有树Tree才能用的方法 if(node.isLeaf())//判断是否叶子节点 Obeject a=(Obeject)node.getUserObject()//返回叶子里面的对象
完整的测试代码
public class test{ public static void main(String args[]){ MyWin window1=new MyWin(); window1.setBounds(12,12,400,300); } } class MyWin extends JFrame implements TreeSelectionListener{ JTextField text1; JButton button1,button2; JTextArea textArea1,textArea2; JLabel label1; JTree tree1; MyWin(){ init(); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } void init(){ DefaultMutableTreeNode root=new DefaultMutableTreeNode("Goods"); DefaultMutableTreeNode nodeTV=new DefaultMutableTreeNode("TV"); DefaultMutableTreeNode nodePhone=new DefaultMutableTreeNode("phone"); DefaultMutableTreeNode tv1=new DefaultMutableTreeNode(new Goods("huangTV",11)); DefaultMutableTreeNode tv2=new DefaultMutableTreeNode(new Goods("yuTV",21)); DefaultMutableTreeNode phone1=new DefaultMutableTreeNode(new Goods("ga",31)); DefaultMutableTreeNode phone2=new DefaultMutableTreeNode(new Goods("bing",11)); root.add(nodeTV); root.add(nodePhone); nodeTV.add(tv1); nodeTV.add(tv2); nodePhone.add(phone1); nodePhone.add(phone2); tree1=new JTree(root); tree1.addTreeSelectionListener(this); setLayout(new GridLayout(1,2)); add(new JScrollPane(tree1)); textArea2=new JTextArea(15,15); add(new JScrollPane(textArea2)); } public void valueChanged(TreeSelectionEvent e){ DefaultMutableTreeNode a=(DefaultMutableTreeNode)tree1.getLastSelectedPathComponent(); if(a.isLeaf()){//是叶子节点? Goods b=(Goods)a.getUserObject(); textArea2.append(b.name+": "+b.price+"\n"); } else textArea2.setText(null); } } class Goods{ String name; double price; Goods(String name,double price){ this.name=name; this.price=price; } }
GUI树组件,表格
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。