public class aaa extends JFrame {
private String filename = "my_xml_file.xml";
private JTree myTree;
public aaa() {
myTree = new JTree();
setBounds(10,10,310,310);
getContentPane().add(new JScrollPane(myTree));
JPanel buttons = new JPanel();
JButton up = new JButton("Up");
up.addActionListener(new UpActionHandler());
buttons.add(up);
getContentPane().add(buttons, BorderLayout.SOUTH);
setVisible(true);
setTree();
}
public void setTree() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultTreeModel dtm = new DefaultTreeModel(root);
for(int i=0; i<10; i++) {
DefaultMutableTreeNode new_node = new DefaultMutableTreeNode("Node "+i);
dtm.insertNodeInto(new_node, root, i);
}
myTree.setModel(dtm);
}
public static void main(String[] args) {
aaa test = new aaa();
}
// This is the action handler for the "Up" button.
private class UpActionHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
TreePath tp = myTree.getSelectionPath();
if(tp == null) {
JOptionPane.showMessageDialog(null, "No node selected", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)tp.getLastPathComponent();
DefaultTreeModel dtm = (DefaultTreeModel)myTree.getModel();
int index = dtm.getIndexOfChild(dtm.getRoot(), dmtn);
if(index != 0) {
dtm.insertNodeInto(dmtn, (DefaultMutableTreeNode)dtm.getRoot(), index-1); // move the node
}
else {
JOptionPane.showMessageDialog(null, "Selected node is first in tree.", "Error", JOptionPane.ERROR_MESSAGE);
}
dtm.reload();
}
}
}
move tree node up
最新推荐文章于 2024-07-19 09:19:29 发布