JTree : Check the level of selection - java

I am using MouseAdapter to check for double clicks on JTree nodes. I want to have some different action depending on the level of the node selected. How can I check the level of node ? Here is the code for the listener:
private MouseAdapter getMouseAdapter(JTree jtree) {
final JTree tree = jtree;
return new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if (selPath != null) {
if (e.getClickCount() == 2) {
String selectedNode = selPath.getLastPathComponent().toString();
// >>>>> check on which level of the tree this node is
}
}
}};
}

You can check the length of the path from selPath to the tree root by first calling the getPath() method of selPath and computing its length.
Object[] array = selPath.getPath();
int depth = array.length;

TreePath path = tree.getSelectionPath();
int level = path.getPathCount();
See the TreePath manual page.

Related

How to expand only leaf nodes with property red_color = true of jtree

I have a jtree with green leaf nodes and reds leaf nodes by implementing a custom CellRenderer.
i am doing this to expand the entire jtree:
expAll.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < jTree1.getRowCount(); i++) {
jTree1.expandRow(i);
}
}
});
but How to create a action to programatically expand my jtree to only leaf nodes that have Red cells?
Thanks here is the final code:
expFail.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Exand the root node
jTree1.expandRow(0);
//Getting the jtree row from the root containing my red and green leaf node
DefaultMutableTreeNode dirNode = (DefaultMutableTreeNode) jTree1.getPathForRow(2).getLastPathComponent();
Enumeration enumDir = dirNode.preorderEnumeration();
while (enumDir.hasMoreElements()) {
//Walking through all nodes of dirNode
DefaultMutableTreeNode enumDirNode = (DefaultMutableTreeNode) enumDir.nextElement();
//If node is leaf and is red (returned by isFailed()) expand to the previous node of this leaf node
if (enumDirNode.isLeaf() && !((LeafNodeObject) enumDirNode.getUserObject()).isFailed()) {
jTree1.expandPath(new javax.swing.tree.TreePath(enumDirNode.getPreviousNode().getPath()));
}
}
}
});

How to edit a JTree node with a single-click

I have a JTree, and would like for its getTreeCellEditorComponent() method to be invoked when I single click on a node. According to the documentation for the DefaultTreeCellEditor class (which I extended), "Editing is started on a triple mouse click, or after a click, pause, click and a delay of 1200 miliseconds." Is there some way to override this behavior, so that a single-click could start the editing process?
The JTree API recommends a MouseListener, but a key binding is also handy. This example invokes startEditingAtPath() and binds to the Enter key:
final JTree tree = new JTree();
tree.setEditable(true);
MouseListener ml = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
int row = tree.getRowForLocation(e.getX(), e.getY());
TreePath path = tree.getPathForLocation(e.getX(), e.getY());
if (row != -1) {
if (e.getClickCount() == 1) {
tree.startEditingAtPath(path);
}
}
}
};
tree.addMouseListener(ml);
tree.getInputMap().put(
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "startEditing");
Addendum: See also this answer regarding usability.
Technically, you can subclass DefaultTreeCellEditor and tweaks its logic to start editing on the first single click:
JTree tree = new JTree();
tree.setEditable(true);
TreeCellEditor editor =
new DefaultTreeCellEditor(tree, (DefaultTreeCellRenderer) tree.getCellRenderer()) {
#Override
protected boolean canEditImmediately(EventObject event) {
if((event instanceof MouseEvent) &&
SwingUtilities.isLeftMouseButton((MouseEvent)event)) {
MouseEvent me = (MouseEvent)event;
return ((me.getClickCount() >= 1) &&
inHitRegion(me.getX(), me.getY()));
}
return (event == null);
}
};
tree.setCellEditor(editor);
There's a usability quirk, though, as now you can't select without starting an edit - which may or may not be your intention.

Jtree get object based on mouse click?

I use this code fragment to perform some action on a tree when the mouse is double-clicked: open a window and get the node which was double clicked by the mouse, but it doesn't return anything, it returns null:
MouseListener ml = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
int selRow = contactTree.getRowForLocation(e.getX(), e.getY());
TreePath selPath = contactTree.getPathForLocation(e.getX(), e.getY());
System.out.println(contactTree.getEditingPath());
Account memberToChat;
if(selRow != -1) {
if(e.getClickCount() == 1) {
}
else if(e.getClickCount() == 2) {
new ChatWindow().setVisible(true);
memberToChat=(Account)node.getUserObject(); // node is declared somewhere in the class as DefaultMutableTreeNode node
System.out.println(memberToChat.getFirstName()+" "+memberToChat.getEmail());
}
}
}
};
for JTree to set proper setSelectionMode
add TreeSelectionListener
example with TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION

Add JPopup menu by right clicking on node in Swing in Java

In GUI,I am displaying one JTree at the left hand side of JPanel. Now for each Node(leaf), on Mouse right click I want to display JPopup menu asking for displaying the statistics about Node in right JPanel.
As i am new to swing,Could any one help with code.
Thanks in Advance.
Regards,
Tushar Dodia.
Use JTree's method
public TreePath getPathForLocation(int x, int y)
Then TreePath
public Object getLastPathComponent()
That returns you desired node from point where user right clicked.
Seem to have caused a bit of confusion (confusing myself ;-) - so here's a code snippet for doing target location related configuration of the componentPopup
JPopupMenu popup = new JPopupMenu();
final Action action = new AbstractAction("empty") {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
};
popup.add(action);
JTree tree = new JTree() {
/**
* #inherited <p>
*/
#Override
public Point getPopupLocation(MouseEvent e) {
if (e != null) {
TreePath path = getClosestPathForLocation(e.getX(), e.getY());
action.putValue(Action.NAME, String.valueOf(path.getLastPathComponent()));
return e.getPoint();
}
action.putValue(Action.NAME, "no mouse");
return null;
}
};
tree.setComponentPopupMenu(popup);
I took #kleopatra solution and changed it slightly.
Maybe it isn't the best way but works for me.
JTree tree = new JTree() {
private static final long serialVersionUID = 1L;
#Override public Point getPopupLocation(MouseEvent e) {
if (e == null) return new Point(0,0);
TreePath path = getClosestPathForLocation(e.getX(), e.getY());
Object selected = path != null ? path.getLastPathComponent() : null;
setComponentPopupMenu(getMenuForTreeNode(getComponentPopupMenu(), selected));
setSelectionPath(path);
return e.getPoint();
}
};
public JPopupMenu getMenuForTreeNode(JPopupMenu menu, Object treeNode) {
if (menu == null) menu = new JPopupMenu("Menu:");
menu.removeAll();
if (treeNode instanceof MyTreeItem) {
menu.add(new JMenuItem("This is my tree item: " + treeNode.toString()));
}
return menu;
}

JTree: how to get the text of selected item?

How can I get the text of selected item in a JTree?
From Java tutorial website on JTree:
//Where the tree is initialized:
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
//Listen for when the selection changes.
tree.addTreeSelectionListener(this);
public void valueChanged(TreeSelectionEvent e) {
//Returns the last path element of the selection.
//This method is useful only when the selection model allows a single selection.
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
if (node == null)
//Nothing is selected.
return;
Object nodeInfo = node.getUserObject();
if (node.isLeaf()) {
BookInfo book = (BookInfo) nodeInfo;
displayURL(book.bookURL);
} else {
displayURL(helpURL);
}
}
DefaultMutableTreeNode selectedElement
=(DefaultMutableTreeNode)tree.getSelectionPath().getLastPathComponent();
.....
System.out.println(selectedElement.getUserObject());
//For multiple selection you can use
TreePath[] treePaths = tree.getSelectionModel().getSelectionPaths();
for (TreePath treePath : treePaths) {
DefaultMutableTreeNode selectedElement = (DefaultMutableTreeNode)treePath.getLastPathComponent();
Object userObject = selectedElement.getUserObject(); //Do what you want with selected element's user object
}
DefaultMutableTreeNode newchild=new DefaultMutableTreeNode(textField.getText());
DefaultMutableTreeNode SelectedNode= (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
DefaultTreeModel treemodel=(DefaultTreeModel) tree.getModel();
JOptionPane.showMessageDialog(null, SelectedNode.getUserObject().toString());
if(SelectedNode!=null)
treemodel.insertNodeInto(newchild, SelectedNode, SelectedNode.getChildCount());

Categories

Resources