Java by API/javax.swing.tree/DefaultTreeModel

Материал из Java эксперт
Перейти к: навигация, поиск

DefaultTreeModel: addTreeModelListener(TreeModelListener l)

 
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
class MyTreeModelListener implements TreeModelListener {
  public void treeNodesChanged(TreeModelEvent e) {
    DefaultMutableTreeNode node;
    node = (DefaultMutableTreeNode) (e.getTreePath().getLastPathComponent());
    try {
      int index = e.getChildIndices()[0];
      node = (DefaultMutableTreeNode) (node.getChildAt(index));
    } catch (NullPointerException exc) {
    }
    System.out.println("New value: " + node.getUserObject());
  }
  public void treeNodesInserted(TreeModelEvent e) {
    System.out.println(e);
  }
  public void treeNodesRemoved(TreeModelEvent e) {
    System.out.println(e);
  }
  public void treeStructureChanged(TreeModelEvent e) {
    System.out.println(e);
  }
}
public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    JTree tree = new JTree(root);
    DefaultTreeModel treeModel = new DefaultTreeModel(root);
    treeModel.addTreeModelListener(new MyTreeModelListener());
    treeModel.insertNodeInto(new DefaultMutableTreeNode("A") ,root,0);
    root.add(new DefaultMutableTreeNode("B"));
    root.add(new DefaultMutableTreeNode("C"));
    
    JScrollPane scrollPane = new JScrollPane(tree);
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.setVisible(true);
  }
}





DefaultTreeModel: insertNodeInto(MutableTreeNode n, MutableTreeNode p, int i)

 
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;
public class MainClass extends JPanel {
  public static void main(String[] args) {
    // create a hierarchy of nodes
    MutableTreeNode root = new DefaultMutableTreeNode("A");
    MutableTreeNode bNode = new DefaultMutableTreeNode("B");
    MutableTreeNode cNode = new DefaultMutableTreeNode("C");
    root.insert(bNode, 0);
    root.insert(cNode, 1);
    bNode.insert(new DefaultMutableTreeNode("1"), 0);
    bNode.insert(new DefaultMutableTreeNode("2"), 1);
    cNode.insert(new DefaultMutableTreeNode("1"), 0);
    cNode.insert(new DefaultMutableTreeNode("2"), 1);
    final DefaultTreeModel model = new DefaultTreeModel(root);
    final JTree tree = new JTree(model);
    final JTextField nameField = new JTextField("Z");
    final JButton button = new JButton("Add");
    button.setEnabled(false);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        TreePath tp = tree.getSelectionPath();
        MutableTreeNode insertNode = (MutableTreeNode) tp.getLastPathComponent();
        int insertIndex = 0;
        if (insertNode.getParent() != null) {
          MutableTreeNode parent = (MutableTreeNode) insertNode.getParent();
          insertIndex = parent.getIndex(insertNode) + 1;
          insertNode = parent;
        }
        MutableTreeNode node = new DefaultMutableTreeNode(nameField.getText());
        model.insertNodeInto(node, insertNode, insertIndex);
      }
    });
    JPanel addPanel = new JPanel(new GridLayout(2, 1));
    addPanel.add(nameField);
    addPanel.add(button);
    tree.addTreeSelectionListener(new TreeSelectionListener() {
      public void valueChanged(TreeSelectionEvent e) {
        TreePath tp = e.getNewLeadSelectionPath();
        button.setEnabled(tp != null);
      }
    });
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200, 200);
    frame.getContentPane().add(new JScrollPane(tree));
    frame.getContentPane().add(addPanel, BorderLayout.SOUTH);
    frame.setVisible(true);
  }
}





DefaultTreeModel: reload()

 
import java.awt.BorderLayout;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
public class MainClass {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Swing Package Hierarchy");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Vector rootVector = new TreeVector("A", new String[] { "a" });
    JTree tree = new JTree(rootVector);
    tree.setRootVisible(true);
    TreeModel model = tree.getModel();
    model.valueForPathChanged(new TreePath(model.getRoot()), "javax.swing");
    ((DefaultTreeModel) model).reload();
    JScrollPane scrollPane = new JScrollPane(tree);
    frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
class TreeVector extends Vector {
  String name;
  TreeVector(String name) {
    this.name = name;
  }
  TreeVector(String name, Object elements[]) {
    this.name = name;
    for (int i = 0, n = elements.length; i < n; i++) {
      add(elements[i]);
    }
  }
  public String toString() {
    return name;
  }
}





extends DefaultTreeModel (Sortable Tree Model)

 
import java.io.File;
import java.util.ruparator;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeNode;
public class MainClass extends JFrame {
  public MainClass(String startDir) {
    super("SortTreeModel Demonstration");
    setSize(300, 400);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    MyFile f = new MyFile(startDir);
    DefaultMutableTreeNode root = new DefaultMutableTreeNode(f);
    SortTreeModel model = new SortTreeModel(root, new TreeStringComparator());
    fillModel(model, root);
    JTree tree = new JTree(model);
    getContentPane().add(new JScrollPane(tree));
  }
  protected void fillModel(SortTreeModel model, DefaultMutableTreeNode current) {
    MyFile pf = (MyFile) current.getUserObject();
    File f = pf.getFile();
    if (f.isDirectory()) {
      String files[] = f.list();
      for (int i = 0; i < files.length; i++) {
        if (files[i].startsWith("."))
          continue;
        MyFile tmp = new MyFile(pf, files[i]);
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(tmp);
        model.insertNodeInto(node, current);
        if (tmp.getFile().isDirectory()) {
          fillModel(model, node);
        }
      }
    }
  }
  public class MyFile {
    File f;
    public MyFile(String s) {
      f = new File(s);
    }
    public MyFile(MyFile pf, String s) {
      f = new File(pf.f, s);
    }
    public File getFile() {
      return f;
    }
    public String toString() {
      return f.getName();
    }
  }
  public static void main(String args[]) {
    MainClass demo = new MainClass(".");
    demo.setVisible(true);
  }
}
class SortTreeModel extends DefaultTreeModel {
  private Comparator comparator;
  public SortTreeModel(TreeNode node, Comparator c) {
    super(node);
    comparator = c;
  }
  public SortTreeModel(TreeNode node, boolean asksAllowsChildren, Comparator c) {
    super(node, asksAllowsChildren);
    comparator = c;
  }
  public void insertNodeInto(MutableTreeNode child, MutableTreeNode parent) {
    int index = findIndexFor(child, parent);
    super.insertNodeInto(child, parent, index);
  }
  public void insertNodeInto(MutableTreeNode child, MutableTreeNode par, int i) {
    // The index is useless in this model, so just ignore it.
    insertNodeInto(child, par);
  }
  private int findIndexFor(MutableTreeNode child, MutableTreeNode parent) {
    int cc = parent.getChildCount();
    if (cc == 0) {
      return 0;
    }
    if (cc == 1) {
      return comparator.rupare(child, parent.getChildAt(0)) <= 0 ? 0 : 1;
    }
    return findIndexFor(child, parent, 0, cc - 1);
  }
  private int findIndexFor(MutableTreeNode child, MutableTreeNode parent, int i1, int i2) {
    if (i1 == i2) {
      return comparator.rupare(child, parent.getChildAt(i1)) <= 0 ? i1 : i1 + 1;
    }
    int half = (i1 + i2) / 2;
    if (comparator.rupare(child, parent.getChildAt(half)) <= 0) {
      return findIndexFor(child, parent, i1, half);
    }
    return findIndexFor(child, parent, half + 1, i2);
  }
}
class TreeStringComparator implements Comparator {
  public int compare(Object o1, Object o2) {
    if (!(o1 instanceof DefaultMutableTreeNode && o2 instanceof DefaultMutableTreeNode)) {
      throw new IllegalArgumentException("Can only compare DefaultMutableTreeNode objects");
    }
    String s1 = ((DefaultMutableTreeNode) o1).getUserObject().toString();
    String s2 = ((DefaultMutableTreeNode) o2).getUserObject().toString();
    return s1.rupareToIgnoreCase(s2);
  }
}