Undo jtree selection
Hi,
I have a jtree, and after each selection a treepath is stored (in an arrayList )of the current selection.
When I want to undo the current selection, and set the previous selection i shall have to use setSelectionPath(treePath);
This again fires an event to valueChanged, with the result that I again get a new storage of a treepath, which I do not want, because this one is to undo the tree selectionpath, not to set another.
public void valueChanged(final TreeSelectionEvent event) {
final ExtendedDefaultMutableTreeNode node = (ExtendedDefaultMutableTreeNode)(event.getPath().getLastPathComponent());
final FileNode fnode = getFileNode(node);
explorerTree.expandPath(node.getPath());
CProcessor.getInstance().do_it(new SetExplorerTreePath(fnode, explorerTree.getSelectionPath()));
}This is my valuechanged method.
CProcessor.getInstance().do_it(new SetExplorerTreePath(fnode, explorerTree.getSelectionPath()));
this line stores the current treepath.
Does anyone know how to solve this problem?
greets, Sjoerd
setSelectionPath(treePath);
This again fires an event to valueChanged, with the
result that I again get a new storage of a treepath,
which I do not wantYou can temporarily remove the TreeSelectionListener:
TreeSelectionListener listener = tree.getTreeSelectionListeners()[0];
tree.removeTreeSelectionListener(listener);
//TODO set new selection
tree.addTreeSelectionListener(listener);
Similar Messages
-
JTree selection problem when using custom renderer and editor
Hello:
I created a JTree with custom renderer and editor.
The customization makes JCheckBox to be the component
responsible for editing and rendering.
The problem is that when I click on the node with the checkbox
the JTree selection model does not get updated.
Without customizations of the editor and renderer the MouseEvent would be fired and BasicTreeUI$MouseHandler.mousePressed() method would call
the selectPathForEvent() method which would be responsible for updating
the selection model. At the same time if I attach a mouse listener to the JTree (customized) I see the events when clicking on the nodes. It seems like the MouseEvent gets lost and somehow as a result of which the selection model does not get updated.
Am I missing something?
Thanks
AlexanderYou probably forgot to call super.getTreeCellRendererComponent(...) at the beginning of your getTreeCellRendererComponent(...) method in your custom renderer.
Or maybe in the getTreeCellEditorComponent(...) of the TreeCellEditor... -
Refine edge tool undoing my selections.
I used the quick select tool and then went into refine edge mask screen. When I use the brush to add or remove selection, it undoes my selection as soon as I release the mouse. Why!?
I tried that among other things.
Finally, we did a complete uninstall of PS -- once with keeping preferences (this didn't work)
and once wilth deleting all preferences (this seem to work)
Note: I do recommend saving all of your Presets before doing this.
Go to Edit > Preset Manager.
Select Preset Type from drop down...
• Brushes
• Swatches
• Gradients
• etc.
Select all by click Cmd + A (Mac) or Ctrl+A (PC)
Then click Save Set...
Save to Desktop or a Folder where you can upload later.
But thanks for your help! -
Hi all,
I've got a JTree that represents a sort of data that I'm going to change dynamically in my application. I'd like to reset the selection of the user to the leaf she has selected before the change to the tree structure.
First of all my tree uses DefaultMutableTreeNode to build each node, and each DefaultMutableTreeNode contains a SingleKeyValue object, that is a key-value object (two strings) and that has an hashcode defined as follows:
public class SingleKeyValue extends BaseKeyValue{
* The key of the database object.
protected String key = null;
* The description of this object.
protected String value = null;
public int hashCode() {
return this.key.hashCode();
I hope the hashcode can help me finding the right object even when its value changes (but the key is the same). The construction of the tree is the following:
DefaultMutableTreeNode root = new DefaultMutableTreeNode("The root");
// iterate and build each node
SingleKeyValue object = new SingleKeyValue("key","value");
DefaultMutableTreeNode node = new DefaultMutableTreeNode(object);
root.add(node);
DefaultTreeModel model = new DefaultTreeModel(root);
JTree tree = new JTree(model);
so the tree is associated to a DefaultTreeModel. Then, when I need to change something in the tree I rebuild the tree and all leafs (with the SingleKeyValues) and rebuild the model:
TreeModel treeModel = this.myTree.getModel();
TreeSelectionModel selectionModel = this.myTree.getSelectionModel();
DefaultTreeModel defaultTreeModel = null;
DefaultTreeSelectionModel defaultTreeSelectionModel = null;
TreePath selectedPath = null;
TreeNode root = null;
Logger.info("SimpleTreePanel.refreshDatabaseView: treemodel "+treeModel + " selectionModel " + selectionModel);
if( treeModel != null && treeModel instanceof DefaultTreeModel ) {
defaultTreeModel = (DefaultTreeModel) treeModel;
root = this.getRoot();
// get the selection
if( selectionModel != null && selectionModel instanceof DefaultTreeSelectionModel ){
defaultTreeSelectionModel = (DefaultTreeSelectionModel) selectionModel;
selectedPath = defaultTreeSelectionModel.getSelectionPath();
Logger.warn("Selection path of the tree: "+selectedPath);
// rebuild the tree
defaultTreeModel.setRoot(root);
// set the selected element
defaultTreeSelectionModel.setSelectionPath(selectedPath);The problem is that after the above code the tree is all closed, no leaf are selected. I guess the problem is with the SingleKeyValueObject because I've tried the default model and it works with, for example, simple strings. Any idea about?
Thanks,
LucaHere's a complete test program that creates a few SingleKeyValue objetcs (objects with a key and a description) and that then places them into a JTree using the DefaultMutableTreeNode. After that, the selection of user is took and one node is changed, but while the selection is working, the reload/refresh of the tree is not.
Any idea about how to work on it?
public class SingleKeyValue extends BaseKeyValue{
* The key of the database object.
protected String key = null;
* The description of this object.
protected String value = null;
// constants related to the type of the table this object refers to
public static final String COMPETENCE = "competenza";
public static final String FAMILY = "famiglia_competenza";
public static final String ROLE = "ruolo";
public static final String PROVINCE = "provincia";
public static final String KNOWLEDGE = "titolo_studio";
public final static String OBJECTIVE = "obiettivo";
public final static String PERSON = "persona";
public SingleKeyValue( String key, String value, String table){
super();
this.key = key;
this.value = value;
this.SQLTable = table;
* @return the key
public final String getKey() {
return key;
* @param key the key to set
public final void setKey(String key) {
this.key = key;
* @return the value
public final String getValue() {
return value;
* @param value the value to set
public final void setValue(String value) {
this.value = value;
* Shows this element.
public String toString(){
String ret;
if( this.showKey ){
ret = this.label + this.key +" { "+ this.value +" }";
else
ret = this.label + this.value;
// trim the string
if( ret.length() > this.maxLength )
return ret.substring(0 , this.maxLength);
else
return ret;
* The hash code of this object is the hash code of the key.
* @return the hash code of the key of the object
public int hashCode() {
return this.key.hashCode();
* Returns true if the object passed is a single key value equals (i.e., with the same key) of this one.
public boolean equals(Object o){
if( o== null || (! (o instanceof SingleKeyValue) ) ) return false;
else
return (this.hashCode() == o.hashCode());
public static void main(String argv[]) throws Exception{
SingleKeyValue skv1 = new SingleKeyValue("Key1","Description1", SingleKeyValue.COMPETENCE);
SingleKeyValue skv2 = new SingleKeyValue("Key1a","Description1a", SingleKeyValue.COMPETENCE);
SingleKeyValue skv3 = new SingleKeyValue("Key1b","Description1b", SingleKeyValue.COMPETENCE);
SingleKeyValue skv4 = new SingleKeyValue("Key2","Description2", SingleKeyValue.COMPETENCE);
SingleKeyValue skv5 = new SingleKeyValue("Key2a","Description2a", SingleKeyValue.COMPETENCE);
SingleKeyValue skv6 = new SingleKeyValue("Key2b","Description2b", SingleKeyValue.COMPETENCE);
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("root");
DefaultMutableTreeNode node1 = new DefaultMutableTreeNode(skv1);
DefaultMutableTreeNode node2 = new DefaultMutableTreeNode(skv2);
DefaultMutableTreeNode node3 = new DefaultMutableTreeNode(skv3);
DefaultMutableTreeNode node4 = new DefaultMutableTreeNode(skv4);
DefaultMutableTreeNode node5 = new DefaultMutableTreeNode(skv5);
DefaultMutableTreeNode node6 = new DefaultMutableTreeNode(skv6);
rootNode.add(node1);
node1.add(node2);
node1.add(node3);
rootNode.add(node4);
node4.add(node5);
node4.add(node6);
JTree tree = new JTree(rootNode);
JFrame f = new JFrame("Tree try");
f.add( new JScrollPane(tree) );
f.setSize(300,300);
f.setVisible(true);
System.out.println("Please select a node within 10 seconds");
Thread.sleep(10000);
// now get the user selection
TreeModel treeModel = tree.getModel();
TreeSelectionModel selectionModel = tree.getSelectionModel();
DefaultTreeModel defaultTreeModel = null;
DefaultTreeSelectionModel defaultTreeSelectionModel = null;
TreePath selectedPath = null;
TreeNode root = null;
if( treeModel != null && treeModel instanceof DefaultTreeModel ) {
defaultTreeModel = (DefaultTreeModel) treeModel;
// get the selection
if( selectionModel != null && selectionModel instanceof DefaultTreeSelectionModel ){
defaultTreeSelectionModel = (DefaultTreeSelectionModel) selectionModel;
selectedPath = defaultTreeSelectionModel.getSelectionPath();
// rebuild the tree
node1.setUserObject(new SingleKeyValue("key20","key changed",SingleKeyValue.FAMILY));
defaultTreeModel.reload();
// set the selected element
defaultTreeSelectionModel.setSelectionPath(selectedPath);
} -
JTree Selection Behavior with Custom TreeCellEditor
I've recently had the need to build a custom TreeCellEditor with a JTree that allows single path selection. I've toyed around with it but don't understand it. When a node is clicked, the editor takes over rendering/handling the cell, and a TreeSelectionEvent is fired from the tree, but the isSelected boolean value passed to the TreeCellEditor is initially false. Then on a second click of the same path in the tree, no TreeSelectionEvent is fired, but the isSelected boolean value is true. It's as if the tree selection is occuring after the editor renders the cell. I would like the cell to appear selected on the first click. Can anyone shed some light on why this is happening and how I can fix it?
I included some code to demonstrate the problem below (though no actual editing takes place; the test code is only to demonstrate how the cells only appear selected with a yellow background after the second click of the same cell; note also that the valueChanged only executes on the first click). This test was run on Windows with Java 1.5.
public class TestTreeCellEditor extends JLabel implements TreeCellEditor {
private String st;
public TestTreeCellEditor() {
setOpaque(true);
public Component getTreeCellEditorComponent(JTree tree, Object value,
boolean isSelected, boolean expanded, boolean leaf, int row) {
this.st = value.toString();
setBackground(isSelected? Color.YELLOW : Color.WHITE);
setText(st);
return this;
public void addCellEditorListener(CellEditorListener l) {
// not important for test
public void cancelCellEditing() {
this.st = null;
public Object getCellEditorValue() {
return st;
public boolean isCellEditable(EventObject anEvent) {
return true;
public void removeCellEditorListener(CellEditorListener l) {
// not important for test
public boolean shouldSelectCell(EventObject anEvent) {
return true;
public boolean stopCellEditing() {
return true;
public class TestTreeCellEditorFrame extends JFrame implements TreeSelectionListener {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
launchGUI();
private static void launchGUI() {
TestTreeCellEditorFrame frame = new TestTreeCellEditorFrame();
JPanel treePanel = new JPanel();
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root node");
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode("Child 1");
rootNode.add(childNode);
childNode = new DefaultMutableTreeNode("Child 2");
rootNode.add(childNode);
JTree testTree = new JTree(rootNode);
testTree.addTreeSelectionListener(frame);
testTree.setCellEditor(new TestTreeCellEditor());
testTree.setEditable(true);
testTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
treePanel.add(testTree);
frame.setContentPane(treePanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
public void valueChanged(TreeSelectionEvent event) {
TreePath path = event.getNewLeadSelectionPath();
if (path != null) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
System.out.println("TreeSelectionEvent on " + node.getUserObject().toString());
}Since my last post, I decided that I do want to be able to edit a cell that is not selected. In particular, when using a tree with checkboxes. What I'm doing for the time being, which works well enough, is to highlight the cell based on the isSelected value in combination with calling tree.stopEditing() in a TreeSelectionListener valueChanged method. This is somewhat of a hack solution, and has the side effect of a cell not appearing selected until the mouseReleased event. I'm still looking for a better solution, but for now it works well enough.
-
Jtree Select node and change leafs icon problem
Hi All,
i create a tree and implement a TreeSelectionListener:
my mission is whenever i select a node i need to change the icon of this node (for now.later i will have to find if it have childrens).
import java.awt.Color;
import java.awt.Component;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
public class TreeView{
DefaultMutableTreeNode top;
JTree tree ;
Color frameColor;
public static ImageIcon NoTSelIcon;
public static ImageIcon SelIcon;
public static String[] name= new String[8];
public TreeView(Color BackColor) {
// TODO Auto-generated constructor stub
top = new DefaultMutableTreeNode("Diagnostics");
this.frameColor=BackColor;
SelIcon = createImageIcon("../Resource/Images/Select.gif");
if (SelIcon == null)
System.err.println("Tutorial icon missing; using default.");
NoTSelIcon = createImageIcon("../Resource/Images/NotSelc.gif");
if (NoTSelIcon == null)
System.err.println("Tutorial icon missing; using default.");
public Component createTreeComponents(){
//Create the nodes.
createNodes(top);
//Create a tree that allows one selection at a time.
tree = new JTree(top);
//TREE LISTENERS
//Treeselction listener
Handler hObject = new Handler();
tree.addTreeSelectionListener(hObject);
//Tree expand/collapse listener
HandlerExpansionListener hObjectExpan = new HandlerExpansionListener();
tree.addTreeExpansionListener(hObjectExpan);
// tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
//set tree background
tree.setBackground(frameColor);
tree.setCellRenderer(new OverrideTreeCellRenderer(frameColor,SelIcon,NoTSelIcon));
return tree;
private void createNodes(DefaultMutableTreeNode top) {
DefaultMutableTreeNode category = null;
DefaultMutableTreeNode SubCategory = null;
DefaultMutableTreeNode SubCategoryBasee = null;
DefaultMutableTreeNode SubSubCategoryBasee = null;
category = new DefaultMutableTreeNode("Dfe");
top.add(category);
//Sub test visible
SubCategory = new DefaultMutableTreeNode("Test Visible");
category.add(SubCategory);
SubCategory.add(new DefaultMutableTreeNode("Son 1"));
SubCategory.add(new DefaultMutableTreeNode("Son 2"));
SubSubCategoryBasee = new DefaultMutableTreeNode("Test Base");
SubSubCategoryBasee.add(new DefaultMutableTreeNode("Grandson 1"));
SubSubCategoryBasee.add(new DefaultMutableTreeNode("Grandson 2"));
SubCategory.add(SubSubCategoryBasee);
class Handler implements TreeSelectionListener {
public void valueChanged(TreeSelectionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("treeSelect event ");
TreePath trph;
trph=arg0.getNewLeadSelectionPath();
int count=trph.getPathCount();
DefaultMutableTreeNode Selnode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
String Name = (String)Selnode.getUserObject();
setSelected(Selnode,true);
int number_ofnodes=getNodeCountBelow((TreeModel)tree.getModel() , Selnode, false);
System.out.println("The Number of nodes under "+Name+"="+number_ofnodes);
tree.setCellRenderer(new IconRenderer(SelIcon,NoTSelIcon,frameColor));
class HandlerExpansionListener implements TreeExpansionListener {
public void valueChanged(TreeSelectionEvent arg0) {
// TODO Auto-generated method stub
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
if (node == null) return;
} // The inner class
public void treeCollapsed(TreeExpansionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("treeCollapsed event ");
public void treeExpanded(TreeExpansionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("treeExpanded event ");
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
//ImageIcon imcon= new ImageIcon(path);
//return imcon;
java.net.URL imgURL = TreeView.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
DefaultMutableTreeNode newnode;
public void setSelected(DefaultMutableTreeNode Selnode ,boolean isSelected)
Enumeration Enchilds=Selnode.children();//ENUMRATE ALL CHILDS FOR THIS NODE
if (Enchilds != null)
while (Enchilds.hasMoreElements())
newnode=(DefaultMutableTreeNode)Enchilds.nextElement();
String NameSel = (String)newnode.getUserObject();
setSelected(newnode,isSelected);
//GETTING THE TREE DEPTH
public int getNodeCountBelow(TreeModel model, Object node, boolean includeInitialNode)
int n = includeInitialNode ? 1 : 0;
for (int i = 0; i < model.getChildCount(node); i ++)
n += getNodeCountBelow(model, model.getChild(node, i), true);
return n;
import java.awt.Color;
import java.awt.Component;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import javax.swing.Icon;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
public class IconRenderer extends DefaultTreeCellRenderer {
private static final long serialVersionUID = 1L;
Icon SelectedIcon;
Icon NotSelectedIcon;
Color BackgroundColor;
boolean Selected=false;
boolean Leaf=false;
boolean IsItaChild=false;
DefaultMutableTreeNode SelctedNode=null;
public IconRenderer(Icon SelIcon,Icon NoTSelIcon,Color Bacground) {
SelectedIcon = SelIcon;
NotSelectedIcon = NoTSelIcon;
BackgroundColor=Bacground;
setBackgroundNonSelectionColor(BackgroundColor);
public Component getTreeCellRendererComponent(JTree tree,Object value,boolean sel,boolean expanded,
boolean leaf,int row,boolean hasFocus)
super.getTreeCellRendererComponent(tree, value, sel,expanded, leaf, row,hasFocus);
Selected=sel;
Leaf=leaf;
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
String s2 = (String)node.getUserObject();
return this;
}my problem is :
when i select a node the the method "getTreeCellRendererComponent"
start to run on the entire tree from buttom to top and than from top to buttom.
for me it waste of time because if has say 100 nodes it wont botthers me.
but i have 20000 nodes and more its take a time.
and for all this nodes i have to make compares.
is there a way to force the DefaultTreeCellRenderer to not run the entire tree???
ThanksYou need to make sure that your TreeModel interprets your group nodes to be non-leaf nodes (one of the methods in the TreeModel interface is called isLeaf). If you are using a DefaultTreeModel with DefaultMutableTreeNode objects, you can use the askAllowsChildren property of DefaultTreeModel and the allowsChildren property of DefaultMutableTreeNode to control this. See the API for more details:
http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultTreeModel.html
http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/tree/DefaultMutableTreeNode.html -
How do I highlight JTree selection ?
Hi,
How do you highlight the selected node in a JTree from code ?
I am deleting a node and want to highlight the preceeding node. I select it via this code :-
jTree.setSelectionPath( newSelectedPath);
jTree.scrollPathToVisible( newSelectedPath);
jTree.repaint();
But that does not highlight the node.
Many thanks in advance,
AaronWith the Move tool selected, this seems to be the only way to enlarge a selection.
What I'd want to do in Joshua's situation though is to draw a marquee around the clips I want to select. The inability to hold down shift or control and draw a second marquee to add more clips to a selection seems like a flaw! Is there a key combination or do I have to always select individual clips (or groups) after the initial selection? -
I know this has been posted on the forum quite a lot and I have looked for it but I have not found any answers as of yet. Here is my delima. I am trying to refresh a JTree by removing the children from the root and then adding the new data. Having saved the selected path before I refresh the tree. I attempt to set it after I have reloaded the data. What sux is that I cannot get it to select the path that I perviously saved. Here is the code sample...
public void refreshTree(BsxJTree _thingTree){
AdminJTreeHelper helper = new AdminJTreeHelper( );
LinkedHashMap _treeData = helper.getTreeStructure( );
TreePath path = _thingTree.getSelectionPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode ).getLastPathComponent( );
DefaultTreeModel model = ( DefaultTreeModel ) _thingTree.getModel( );
DefaultMutableTreeNode root = ( DefaultMutableTreeNode ) model.getRoot( );
root.removeAllChildren( );
//uses the LinkedHashMap to load the tree
populateTree( _treeData, _thingTree );
_thingTree.expandToPath( node );
}This is a method that I have written to extend the JTree
//I know this code below works b/c I have tested it.
* Expands the tree to make the node visible. This method beefs up the
* expandPath method in JTree where it expandeds the path to the node
* passed to it if it is expandable. Otherwise if the node is not
* expadable it will expand the nodes parent so that the node is
* visible. The node will then beselected.
* @param node the node to expand to
* @return the path what was expanded. Either the nodes path or the parents
* path.
public TreePath expandToPath( DefaultMutableTreeNode node )
TreePath path = new TreePath( node.getPath( ) );
if ( node.isLeaf( ) )
TreePath parentPath = path.getParentPath( );
expandPath( parentPath );
setSelectionPath(path);
return parentPath;
else
expandPath( path );
setSelectionPath(path);
return path;
}for all of you that actually care... (those who are searching the forums for answers. I have created the following code which works to get the node which a userObject resides. Note this code can only be used when the JTree contains DefaultMutableTreeNodes (only nodes that a userObject can be attached).
I use this code for refreshing a JTree and then reselecting the object that was selected prior to the refresh. Code is compilable.
Thanks for all your help but I think I am going to award the duke dollars to my self on this one.
* Searches the JTree for the for any UserObject that is equal to the passed
* userObject.
* <p>
* <b>NOTE:</b>This only works when the tree nodes are
* DefaultMutableTreeNodes. Those are the only nodes that you can attach a
* user object to.
* </p>
* Because most objects don't specify a .equals(Object) method the objecs
* are considered equal if they have the same toString() value.
* @param userObject the object to find in the tree
* @return the node that contains the userObject
public DefaultMutableTreeNode findUserObject( Object userObject )
TreeNode root = ( TreeNode ) getModel( ).getRoot( );
DefaultMutableTreeNode node = getUserObjectNode( root, userObject );
if ( node == null )
return null;
else
return node;
* Visit all nodes in a tree and check to see if that node contains the
* UserObject. If the node is found return the tree path for the node.
* @param node node to process
* @param userObject JTree to search.
* @return the node that contains the userObject
private DefaultMutableTreeNode getUserObjectNode( TreeNode node,
Object userObject )
// node is visited exactly once
DefaultMutableTreeNode foundNode = null;
if ( node instanceof DefaultMutableTreeNode )
DefaultMutableTreeNode fn = ( DefaultMutableTreeNode ) node;
String userObjectString = userObject.toString( );
String nodeObjectString = fn.getUserObject( ).toString( );
if ( userObjectString.equals( nodeObjectString ) )
return fn;
if ( node.getChildCount( ) >= 0 )
for ( java.util.Enumeration e = node.children( );
e.hasMoreElements( ); )
TreeNode n = ( TreeNode ) e.nextElement( );
foundNode = getUserObjectNode( n, userObject );
if ( foundNode != null )
return foundNode;
return null;
} -
I have a problem trying to select a node of a JTree using JDK 1.3.1 and JDK 1.4 beta 3. I use a JTree with a DefaultTreeModel and DefaultMutableTreeNodes.
Before the tree became visible it has all the nodes loaded but not visible. Then I want to select a path of the tree using a node (DefaultMutableTreeNode) but I not able to do it.
The path isn't selected and isn't visible.
I use the following code:
jTree.setExpandsSelectedPaths(true)
jTree.setSelectionPath(new TreePath(node.getPath()));
//I've also tried with
jTree.expandPath(new TreePath(dmtn.getPath()));Thanks.Fair enough. I guess I need to do a bit more reading.
You have to create a new TreePath object because the
getPath() method of DefaultMutableTreeNode returns an
array of TreeNodes where as the setSelected method of
JTree requires a TreePath object.
Why are you creating a new path with the contents ofa
call to getPath?
wouldn't node.getPath() be what you want toexpend/set
visible/scroll to etc
try it without creating a new TreePath -
How can I force a JTree to change selection on a mouse release rather than the mouse press?
Background - I have a component that uses a JTree as a navigation device - click on a node in the tree and the right side of the GUI shows a particular panel. Some panels allow user to drag a node from the navigation tree into the panel on the right side. The drag and drop is working fine, except that when a node in the tree is clicked, it changes which panel is showing and the place that I wanted to drag to is no longer visible.
I've temporarily worked around it by adding a "locked" checkbox to the navigation tree, so that if the checkbox is locked then I just set the tree selection back to what it was when the selection changes. This is not very user friendly. Ideally, I'd like the selection in the tree to change only when the mouse is released. Alternately, I could live with only starting a drag when the CTRL key was pressed or something similar.mclabo01 wrote:
How can I force a JTree to change selection on a mouse release rather than the mouse press?This is what I might try:
-- use getMouseListeners to save the array of MouseListener[] to an instance field
-- iterate over the array and removeMouseListener all of them
-- add a single MouseListener
---- in mouseReleased, construct a new MouseEvent from the ME received as parameter, changing the ID from MOUSE_RELEASED to MOUSE_PRESSED
---- iterate over the array and invoke mousePressed on each listener with the constructed event
May work, may not. And you may have to collect the MouseListeners after the tree is made visible.
db
edit It appears there's no need to modify the MouseEvent. Proof of concept (may need some tuning for different treatment of each mouse button):import java.awt.event.*;
import javax.swing.*;
public class MouseReleaseSelectTree {
MouseListener[] listeners;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new MouseReleaseSelectTree().makeUI();
public void makeUI() {
JTree tree = new JTree();
listeners = tree.getMouseListeners();
for (MouseListener listener : listeners) {
tree.removeMouseListener(listener);
tree.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
for (MouseListener listener : listeners) {
listener.mouseClicked(e);
@Override
public void mousePressed(MouseEvent e) {
@Override
public void mouseReleased(MouseEvent e) {
for (MouseListener listener : listeners) {
listener.mousePressed(e);//pressed);
@Override
public void mouseEntered(MouseEvent e) {
for (MouseListener listener : listeners) {
listener.mouseEntered(e);
@Override
public void mouseExited(MouseEvent e) {
for (MouseListener listener : listeners) {
listener.mouseExited(e);
JFrame frame = new JFrame();
frame.add(new JScrollPane(tree));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}Edited by: DarrylBurke -
Polygon lasso in photoshop cs3 (FUTURE REQEST: "Undo last selection" )
I'm working on a large image and sometimes I use polygon lasso tool to crop desired region on image but sometime I accidentally click the mouse to the undesired region and I can't undo the last selection.
Just hit the backspace/delete key, and it will step back through the click points you have made.
-
Cancel JTree selection event ?
Hello,
I have defined a user object in the DefaultMutableTreeNode that holds a flag for disabled nodes - Now I would like to cancel events from the user when this node is being selected, also I would like to make this node appear disabled.
How should I do this with JTree embedded inside an applet ?
Thank you,
Maxim.My rough idea is, store your previous selection, when you get selection change event, check if the node is disabled, if so, set the selection back to previous selection. Also, you can implement TreeCellRender interface, make the node's background gray to let user feel it is disabled.
-
Hi:
It is posible to change the width of the selection rectangle in a JTree?? I would like the right side of the rectangle strike the rigth side of the tree for all the items in it.
Thanks in advance...import java.awt.*;
import javax.swing.*;
class CharWidthInTextField {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
JTextField tf = new JTextField();
tf.setText( tf.getFont().toString() );
JOptionPane.showMessageDialog( null, tf );
tf.setFont( new Font(Font.MONOSPACED, Font.PLAIN, 12) );
tf.setText( tf.getFont().toString() );
JOptionPane.showMessageDialog( null, tf );
EventQueue.invokeLater(r);
} -
Hi,
Is it possible to have a JTree whose nodes are selectable only at a predefined level? For instance, in one JTree the user would only be able to select nodes at level 1. The children would not be selectable, but would just provide information to the user. Similarly, In a different JTree that I need to create, the level 1 and 2 nodes would NOT be selectable, but the nodes at level 3 would be.
I have examined some of the methods under JTree such as setSelectionRows but am not sure how to implement it using this. The JTree data at all levels will come from a database. I can supply it as a Vector easily enough.
Thank you for any help you can provide! Some sample code would be great.
LynetteIt sounds like a general description of your problem is that you want some nodes to be selectable and others not to be, and that in each case you have an algorithm that describes which nodes may be selected.
One way to do this would be to apply a TreeSelectionListener to the JTree, and have that listener censor the selections. By that I mean that when it sees an attempt to select a non-selectable node, it would simply modify the list of selected nodes to exclude that node (with or without notifying the user, whatever you wanted).
Another way that might work is to create a class that overrides DefaultTreeSelectionModel. In particular, override the addSelectionPath(TreePath) method to do nothing if the TreePath parameter represented a non-selectable node, otherwise to call super.addSelectionPath. Then assign an object of this class to be your JTree's TreeSelectionModel. This would be a cleaner design, if it actually worked, but I haven't tried it myself. -
The selected note in the JTree will not be displayed (highlighning)....why ? The node is selected...
TreePath tpath = mainFrame.getTreeApplications().getSelectionModel().getSelectionPath();
mainFrame.getTreeApplications().clearSelection();
mainFrame.getTreeApplications().updateUI();
mainFrame.getTreeApplications().getSelectionModel().setSelectionPath(tpath);http://www.physci.org/codes/sscce.jsp
Maybe you are looking for
-
Software to connect Deskjet 3070A to wifi no longer available
My printer is AirPrint capable, but to set up the connection to wifi, you have to connect it to a computer and use a piece of HP software on the computer to set it up. You can't connect to wifi networks on the printer itself. My wifi network has chan
-
I can't download a few songs in my iPod
I can't download a few songs (in iTunes) in my iPod (bought in my iMac)
-
I can't compile this, why?
I do not possess any means of compiling any .java file that imports javax.* or anything J2SE-related, thus, I have to compile it remotely on a remote host (www.myjavaserver.com), however, for some reason this file will not compile but will not produc
-
Comprariais la Matrox RXT 100?
Quiero dar el salto y comprar una buena capturadora que trabaje video en tiempo real. Habitualmente utilizo el PPro, porque me parece francamente bueno y he leido que esta tarjeta está diseñada especificamente para el programa de A¡dobe. Los que la t
-
When ever I try to download creative cloud it disappears and doesn't fully install
There is an error whenever I try to download creative cloud