JAVA JTree的使用

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;




/**
 * 一个JTree的维护代码。重点在
 * 1)获取选择节点的方式
 * 2)在JTree中增加Jpopmenu的方式
 * 3)删除节点
 * 4)修改节点
 * @author miao
 *
 */
public class ShowTree extends JTree {
public ShowTree(String rootName)
{
super();
setEditable(true);   
DefaultMutableTreeNode node = new DefaultMutableTreeNode(rootName);
DefaultTreeModel treeModel = new DefaultTreeModel(node);
setModel(treeModel);

AddPopMenu();

}

/**
* 增加数据树的节点
* @param strSubNode
*/
public void AddTree(String strSubNode)
{
String inputStr = JOptionPane.showInputDialog("请输入节点名称");
if (inputStr.length()>0)
{
strSubNode = inputStr;
}

DefaultMutableTreeNode node = (DefaultMutableTreeNode)getLastSelectedPathComponent();

DefaultMutableTreeNode subNode = new DefaultMutableTreeNode(strSubNode);
node.add(subNode);
updateUI();
}

public void AddPopMenu()
{
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem item = new JMenuItem("增加");

item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
AddTree("newSubNode");
}
});
popupMenu.add(item);

item = new JMenuItem("删除");
item.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
DelTree();
}
});
popupMenu.add(item);

item = new JMenuItem("修改");
item.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
EditTree();
}
});
popupMenu.add(item);

setComponentPopupMenu(popupMenu);
}

/**
* 只有输入回车才能修改树形结构的节点值
*/
private void EditTree()
{
startEditingAtPath(getSelectionPath());
}

public void DelTree()
{
int option = JOptionPane.showConfirmDialog(null, "确定要删除该节点吗?");
if(option==0)
{
System.out.println(option);
DefaultMutableTreeNode node = (DefaultMutableTreeNode)getLastSelectedPathComponent();
node.removeFromParent();
updateUI();
}
}

public static void main(String[] args)
{
ShowTree showTree = new ShowTree("this is root");
JFrame jFrame = new JFrame();
jFrame.getContentPane().add(showTree);
SwingConsole.run(jFrame,0, 0);
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值