Charles Bell
Posts: 519
Nickname: charles
Registered: Feb, 2002
|
|
Re: Swing Jtree Req. !!
|
Posted: Jul 12, 2002 6:22 PM
|
|
Look at this: http://www.quantumhyperspace.com/SourceBank/TreeEditor.java
/* TreeEditor.java * @author: Charles Bell * @version: 4/13/2002 */
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.accessibility.*; import javax.swing.*; import javax.swing.text.*; import javax.swing.event.*; import javax.swing.tree.*;
public class TreeEditor implements ActionListener, TreeSelectionListener{
String rootNodeName = "Root"; JFrame f; JTree tree; DefaultTreeModel treemodel; boolean debug = true; JTextArea display; String oldString = ""; //used to save cell editor results String newString = ""; //used to save cell editor results public static void main(String[] args){ TreeEditor treeeditor = new TreeEditor(); treeeditor.init(); }
public void init(){ f = new JFrame("TreeEditor"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(Toolkit.getDefaultToolkit().getScreenSize()); //display will show the results of what is happening behind the scenes display = new JTextArea(10,50); display.setEditable(false); f.getContentPane().add(new JScrollPane(display),"South"); TreeNode rootnode = new DefaultMutableTreeNode(rootNodeName,true); treemodel = new DefaultTreeModel(rootnode);
tree = new JTree(treemodel); tree.setEditable(true); tree.setSelectionRow(0); //so that calls to old value will not be null //Set up the editor for the cells. final StringField stringField = new StringField(rootNodeName, rootNodeName.length()+5);
DefaultCellEditor stringeditor = new DefaultCellEditor(stringField) { //Override DefaultCellEditor's getCellEditorValue method //to return an Integer, not a String: public Object getCellEditorValue() { return stringField.getValue(); } }; tree.setCellEditor(stringeditor);
tree.addTreeSelectionListener(this); //add a mouse listener so you can see mouse how mouse clicks enter the action MouseListener ml = new MouseAdapter() { public void mousePressed(MouseEvent e) { int selRow = tree.getRowForLocation(e.getX(), e.getY()); TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); if(selRow != -1) { if(e.getClickCount() == 1) { println("Single click on row: " + selRow + " path: " + selPath.toString()); }else if(e.getClickCount() == 2) { println("Double click on row: " + selRow + " path: " + selPath.toString()); }else if(e.getClickCount() == 3) { println("Triple click on row: " + selRow + " path: " + selPath.toString()); } } } }; tree.addMouseListener(ml);
f.getContentPane().add(new JScrollPane(tree),"Center"); JPanel buttonPanel = new JPanel();
JButton addsiblingbutton = new JButton("Add Sibling"); JButton addchildbutton = new JButton("Add Child"); JButton makeleafbutton = new JButton("Make Leaf"); JButton deletebutton = new JButton("Delete"); JButton exitbutton = new JButton("Exit");
buttonPanel.add(addsiblingbutton); buttonPanel.add(addchildbutton); buttonPanel.add(makeleafbutton); buttonPanel.add(deletebutton); buttonPanel.add(exitbutton);
addsiblingbutton.addActionListener(this); addchildbutton.addActionListener(this); makeleafbutton.addActionListener(this); deletebutton.addActionListener(this); exitbutton.addActionListener(this);
JPanel labelPanel = new JPanel(); labelPanel.setLayout(new GridLayout(4,1)); labelPanel.add(new JLabel("Single click a node to select it. Double click a node to expand or collapse it.")); labelPanel.add(new JLabel("Editing is started on a triple mouse click, or after a click, pause, click and a delay of 1200 miliseconds.")); labelPanel.add(new JLabel("Depress Escape to exit the node and restore its original value.")); labelPanel.add(new JLabel("Selecting a different node saves the changes in the last node edited.")); JPanel toppanel = new JPanel(); toppanel.setLayout(new BorderLayout()); toppanel.add(buttonPanel,"North"); toppanel.add(labelPanel,"Center"); f.getContentPane().add(toppanel,"North");
//f.pack(); f.show(); }
public void actionPerformed(ActionEvent ae){ String command = ae.getActionCommand(); println("command:" + command); if (command.compareTo("Exit") ==0) System.exit(0); DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent(); println("selectedNode:" + selectedNode.toString()); if (selectedNode == null) { return; //since no node was selected then don't do anything }else if (command.compareTo("Delete") ==0){ if (selectedNode.getParent() != null){ treemodel.removeNodeFromParent(selectedNode); return; } } else if (command.compareTo("Add Sibling") ==0) { DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New"); DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent(); if (parentNode != null) { treemodel.insertNodeInto(newNode,parentNode, parentNode.getIndex(selectedNode)+1); } TreeNode[] nodes = treemodel.getPathToRoot(newNode); TreePath path = new TreePath(nodes); tree.scrollPathToVisible(path);
}else if (command.compareTo("Add Child") ==0) { DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New"); treemodel.insertNodeInto(newNode,selectedNode, selectedNode.getChildCount()); TreeNode[] nodes = treemodel.getPathToRoot(newNode); TreePath path = new TreePath(nodes); tree.scrollPathToVisible(path);
}else if (command.compareTo("Make Leaf") ==0) { selectedNode.setAllowsChildren(false); selectedNode.removeAllChildren(); treemodel.reload(selectedNode); } } public void valueChanged(TreeSelectionEvent tse){ println("TreeSelectionEvent: valueChanged"); TreePath oldtreepath = tse.getOldLeadSelectionPath(); TreePath newtreepath = tse.getNewLeadSelectionPath(); Object oldobject= oldtreepath.getLastPathComponent(); if (debug) println("Old Object String: " + oldobject.toString()); //the following line eill change the value of the object at oldtreepath to // oldString which was saved from the last cell edit of that node treemodel.valueForPathChanged(oldtreepath,oldString); Object revisedoldobject= oldtreepath.getLastPathComponent(); if (debug) println("Revised Object String: " + revisedoldobject.toString()); Object newobject= newtreepath.getLastPathComponent(); if (debug) println("New Object String: " + newobject.toString()); }
/** Convenience method to display actions. */ public void println(String s){ display.append(s + "\n"); display.setCaretPosition(display.getText().length()); }
/** Adapted from the TableEditDemo.java program in the Java Tutorial. * The Java tutorial demo program used a WholeNumberField which accepted Whole Nmbers. * This one takes Strings so that intermediate values of the string can be saved for inertion * into the previously selected node when the user canges node selection without hitting enter * to save. */ class StringField extends JTextField implements KeyListener{ private Toolkit toolkit; private String originalvalue; public StringField(String value, int columns) { super(columns); toolkit = Toolkit.getDefaultToolkit(); originalvalue = value; setValue(value); addKeyListener(this); }
public String getValue() { return getText(); }
public void setValue(String value) { setText(value); }
protected Document createDefaultModel() { return new StringDocument(); }
public void keyPressed(KeyEvent keyevent){ if (keyevent.getKeyCode() == KeyEvent.VK_ESCAPE){ TreeEditor.this.println("Debug: Escape depressed resetting to original value"); setValue(originalvalue); setText(originalvalue); oldString = originalvalue; newString = originalvalue; } } public void keyReleased(KeyEvent keyevent){ } public void keyTyped(KeyEvent keyevent){ } protected class StringDocument extends PlainDocument { public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { char[] source = str.toCharArray(); char[] result = new char[source.length]; int j = 0; for (int i = 0; i < result.length; i++) { result[j++] = source[i]; toolkit.beep(); //this line causes a beep every time you enter a new text value in the cell editor //TreeEditor.this.println("inserted Characters: " + source[i]); } TreeEditor.this.println("inserted Characters: " + new String(source)); super.insertString(offs, new String(result, 0, j), a); oldString = newString; newString = getValue(); TreeEditor.this.println("Debug: oldString: " +oldString + "\tnewString: " +newString); } } } }
|
|