Doubt in JTree...

I am having a JTree with one root node and 2 child nodes.Each child node have some sub child nodes..
What i have to do is on right click of a subchild node, i have to get a popup option.how to do it??
I used mouselistener and checked popuptrigger..and i am able to generate the popup,but its getting poped up everywhere in the panel where i am having JTree..I want to get popup only on right click on the node..
thanks for your reply in advance

You could use
public class AutomatedTreeMouseHandler extends MouseAdapter {
     public void mousePressed(MouseEvent e) {
          JTree tree = (JTree) (e.getSource());
          int x = e.getX();
          int y = e.getY();
          TreePath path = tree.getPathForLocation(x, y);
          if (path != null) {
               // generate your popup here
}Denis Krukovsky
http://sourceforge.net/projects/dotuseful/

Similar Messages

  • Help Needed in Building JTree

    HI,
    I've a doubt in Building a JTree.It wud be helpful if some one helps me with a better logic for building this Tree..
    I have a tree like this:
    root
    |
    A--B--C--D
    A--B--C--D
    A--B--C
    A--B--C--E--F
    I have the tree nodes like this . i need to merge the nodes like this
    root
    |
    A
    |
    -- B
    |
    --C
    |
    --D
    --E
    |
    --F
    I've tried it in few ways. It doesn't seems to be working.. Can some one help me in giving me a better logic in doing this

    Hello,
    When updating the tree, do not access the tree nodes directly. Update the tree via its (TreeModel).
    to get the model of your JTree use
    DefaultTreeModel treeModel = (DefaultTreeModel)myTree.getModel();to add nodes use the method
    treeModel.insertNodeInto(newChild,parent,offset);and remove nodes using
    treeModel.removeFromParent(nodeToRemove);--
    Regards,
    Ahmed Saad

  • Highlighting nodes in a JTree

    Hi,
    I'd like to know how I can produce the efect of highlighting nodes in a JTree when the mouse moves over the JTree.
    Thanks

    You say to get the mouseevent coordinates with a mouse
    listener, but which component should be the caller of
    the methos addMouseListener?
    If I choose the jtree, I can't get the 'mouseevent
    coordinates' each time the mouse moves over a node,
    because the methods mouseEntered and mouseExited are
    invoked just once (when the mouse enter inside the
    jtree's area (mouseEntered), and when the mouse gets
    out the jtree's area(mouseExited)), so I can't change
    the boolean field to true for nodes which have the
    mouse over.just use mouseMoved of the MouseMotionListener.
    however, i have my doubts that you will have a lot of fun with the suggested method (correct though it is).
    at least make sure you only call the repaint method if the mouse moved into a new node. you might want to try the the nodeChanged method, that way you don't repaint the whole tree every time.
    thomas

  • How do I get a JTree to display a String?

    I'm fiddling around with JTree right now, but I want to be able to format the display string in the table.
    When I create a new item, I want that item to be listed as Item 2, or Item 3, in the tree. How can I do that?
    How do I change the display string of the TreeNode holding the object, without altering the actual object?
    PS: JTree looks so horribly complicated and outdated, did Sun release any newer implementations of trees yet?

    It certainly looks modular...I don't doubt that...
    But its so complicated to achieve even the simplest of tasks. Perhaps a few more convenience methods or basic implementations should be provided?
    Anyway, I've read up on TreeCellRenderer and it seems like it can handle what I want (change the displayed string), it also seems like I need to create my own renderer. Now doesn't that sound like a bit too much work when I all I want is for it to paint "Item 2" instead of "Item@5124f20" ??

  • Question on JTree

    Hi All,
    I have a main root as VNVExecutor in JTree and one of its sub tree is User Manual.So i am seperating the whole with left component as JTree and Right Components as JScrollPane by using JSplitPane.Now my doubt is when i click on subtree component i.e. usermanual a JTextField/JButton..watever may be the component that has to be added.Can ay one help me out in telling how to perform this??
    Thanks in advance.
    regards,
    Viswanadh

    Read the Swing tutorial on [How to Use Trees|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html] for a working example. The example there disiplays text in a text area, so you would customize it to do what you want.

  • Set icon for toggle control of JTree node.

    hi.
    Just a question.
    I am looking towards setting the icons of the JTree by this i mean the icon that you click on
    to open say a node .
    I know you can set the icons of the nodes by setIcon inside your TreeCellRenderer but i doubt that
    that will set the icon that is to the left ot your label.
    Has anyone gone down this path recently.
    The class BasicTreeUI has a method
    called paintExpandControl( Graphics g,
    Rectangle clipBounds,
    . Insets insets,
    Rectangle bounds,
    TreePath path,
    int row,boolean isExpanded,
    boolean hasBeenExpanded,
    boolean isLeaf)
    Hopefull this is a method that can paint the toggle node so has anyone subclassed BasicTreeUI and done something like this recently.
    Any advise on the topic is really appreciated.
    Thank you.

    Yes, they are icons and they are called "handles". The easiest way to change then is to use UIManager.
    If you haven't done so before, look through the hash table UIManager.getLookAndFeelDefaults().
    import java.awt.*;
    import java.net.*;
    import javax.swing.*;
    public class TreeIcons {
         public static void main(String[] args) throws MalformedURLException {
              String prefix = "http://forum.java.sun.com/images/";
              UIManager.put("Tree.openIcon", new ImageIcon(new URL(prefix + "dont_save.gif")));
              UIManager.put("Tree.closedIcon", new ImageIcon(new URL(prefix + "save.gif")));
              UIManager.put("Tree.leafIcon", new ImageIcon(new URL(prefix + "forum_new.gif")));
              UIManager.put("Tree.expandedIcon", new ImageIcon(new URL(prefix + "email_faded.gif")));
              UIManager.put("Tree.collapsedIcon", new ImageIcon(new URL(prefix + "email.gif")));
              JFrame f = new JFrame("TreeIcons");
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.getContentPane().add(new JTree());
              f.setSize(new Dimension(300,400));
              f.setLocationRelativeTo(null);
              f.setVisible(true);
    }

  • Getting back the JTree Instance

    Hi:
    I have an instance of a node (DefaultMutableTreeNode) that was copied from a JTree and pasted in the system clip board. In another part of the application I retrieve the node. Now based on the node is it possible to get a reference back to the original JTree?

    I doubt it since a TreeNode is part of the model, not part of the UI. The UI has a handle to the model, but not vice versa.

  • Doubt - urgent

    hi
    i have a doubt in java. do java have any classed to list the drives, files and folder in a GUI format.. as windows does. i know there are controls in VB for listing the drives, folders and file. is there any class in java of this sort
    charles

    Both Aldaris and Yogee have the correct answer but in different ways. Aldaris' answer will give you the listing although it ideally, should recurse through sub-directories. Yogee gives you a GUI component to choose or save files. A third alternative would be to use a JTree. There are numerous examples of trees containing a directory structure, on the web.
    Good luck.

  • JTree text overlapping when setting LF to native on WinXP

    Hi,
    Using (JDK1.5) under Windows XP
    I have a little program that presents a directory structure in a Windows Explorer type of way. I am using JTree to achieve this.
    I am using
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());to get it to look like Windows LF.
    However, when I tried to do:
    tree.setFont(new Font("Dialog", Font.BOLD, 20));The text of the nodes starts to overlap with its neighbor nodes.
    I even tried this on the code that comes as part of "How to use Trees" tutorial on java.sun.com (TreeIconDemo.java). Same thing happens.
    Any ideas or workarounds for this?
    Your help would be greatly appreciated.
    Thanks,
    Yaakov.

    I'll move it there, but I doubt you'd get much better response. Hopefully you will . Next time, to contact a moderator with requests like that, just 'report' the post.

  • How to put table relations in a hierarchical Jtree

    Hi everyone !
    My Problem is as following:
    1. I've got a generic Database (over JDBC-ODBC)
    2. I'v got an application with a JTree
    3. I want to get the relations between tables
    4. Those relations should be put in a hierarchical tree (namely JTree) to get a complete map of the Database!
    I know, i have to get informations from the database schemas, but i don't know, how to handle them :-(
    The database is in any relatioal format (e.g. Access) and what i want, is a hierarchical map of it in a JTree...
    Example code is appreciated (if someone has solved it already !?!)
    Kevin

    Hi Kevin,
    I didn't want to be offending.
    Sorry, if it has sounded this way for you!
    Was it a problem to tell you things you already knew?
    I didn't know that you knew them, and from your question I assumed you didn't.
    I don't doubt that you are a DB programmer.
    But I have not yet a clear feeling what you want to get out in your JTree at the end.
    You make the tables to nodes in the tree and their columns to their children. For one table, ok.
    Obviously you want to follow the joins and so skip from table to table.
    So the columns of the joined table are added to those of the first table. Ok.
    The DatabaseMetaData class should be able to tell you the primary keys - by getPrimaryKeys() -
    and the foreign keys - by getExportedKeys() and getImportedKeys() - of your tables.
    Do you make 1 JTree for each single table? Then I don't doubt you get a flat hierarchy.
    But I had thought, you want to get all the tables in 1 graphical structure,
    and for this I still don't understand, what you do with m-to-n-realtionships (which I called links).
    Example:
    table "program", table "pc"
    Each program can be installed on n pcs, each pc can have n programs installed.
    Probably you use a table program_pc to implement this relationship.
    So table program_pc is joined to table program (program_pc.program_id = program.program_id)
    and also to table pc (program_pc.pc_id = pc.pc_id).
    How would you solve this?
    I'm really interested.
    Yours
    Hartmut

  • JTree - full row select

    Hi,
    I would like to make the JTree tree items selectable/appearing like in the eclipse "Package Explorer". A tree item should become selected when the user clicks anywhere in it's row. Additionally the background color of the full row should be the selection-background color not only the label background.
    Any ideas how to do this ? I hope there is a solution for this, but I have doubts about it because of how the CellRenderer thing works.
    Thanks in advance,
    Christian

    Hi
    The mouse listener in that solution doesn't properly handle SHIFT/CTRL.
    This should work better:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Insets;
    import java.awt.Rectangle;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.UIManager;
    import javax.swing.plaf.basic.BasicTreeUI;
    import javax.swing.tree.TreePath;
    public class ExplorerTreeUI extends BasicTreeUI {
        private Color backgroundSelectionColor = null;
        private RowSelectionListener sf = new RowSelectionListener();
        protected void installDefaults() {
            super.installDefaults();
            backgroundSelectionColor = UIManager.getColor("Tree.selectionBackground");
        protected void paintRow(Graphics g, Rectangle clipBounds,
                Insets insets, Rectangle bounds, TreePath path,
                int row, boolean isExpanded,
                boolean hasBeenExpanded, boolean isLeaf) {
            // Don't paint the renderer if editing this row.
            if (editingComponent != null && editingRow == row)
                return;
            if (tree.isRowSelected(row)) {
                int h = tree.getRowHeight();
                g.setColor(backgroundSelectionColor);
                g.fillRect(clipBounds.x, h*row, clipBounds.width, h);
            super.paintRow(g, clipBounds, insets, bounds, path, row, isExpanded,
                    hasBeenExpanded, isLeaf);
        protected void installListeners() {
            super.installListeners();
            tree.addMouseListener(sf);
        protected void uninstallListeners() {
            tree.removeMouseListener(sf);
            super.uninstallListeners();
        private class RowSelectionListener extends MouseAdapter {
                         * Listener for selecting the entire rows.
                         * @author Kirill Grouchnikov
            @Override
            public void mousePressed(MouseEvent e) {
                if (!tree.isEnabled())
                    return;
                TreePath closestPath = tree.getClosestPathForLocation(e.getX(), e.getY());
                if (closestPath == null)
                    return;
                Rectangle bounds = tree.getPathBounds(closestPath);
                // Process events outside the immediate bounds -
                // This properly handles Ctrl and Shift
                // selections on trees.
                if ((e.getY() >= bounds.y)
                        && (e.getY() < (bounds.y + bounds.height))
                        && ((e.getX() < bounds.x) || (e.getX() > (bounds.x + bounds.width)))) {
                    // fix - don't select a node if the click was on the
                    // expand control
                    if (isLocationInExpandControl(closestPath, e.getX(), e.getY())) {
                        return;
                    selectPathForEvent(closestPath, e);
    }

  • Serialization of JTree Object

    i need to serialize the JTree object .
    1) i used XMLEncoder and XMLDecoder
    2)and i used ObjectOutputStream and ObjectInputStream
    Please help me with sample program
    Solution would be really helpful.

    krish1985 wrote:
    i need to generate the JTree dynamically.for that i need to save the
    object in a file(Serialization)Why? I very much doubt you do. The JTree is simply a view on some data. It's that data you want to serialize in some way

  • Applet doubt

    I m taking this code from else where .but in o/p after login if u see on right side i get jtree-color-sports-food--like this menu.If i want my own menu how can i do this ,if any one have idea pls post me to [email protected] or post here
    java code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class LoginApplet2 extends JApplet {
    public void init() {
    add( new MainGui(), BorderLayout.CENTER );
    validate();
    public static void main(String[] args) {
    Runnable r = new Runnable() {
    public void run() {
    JFrame f = new JFrame("Log-In app.");
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    f.add( new MainGui(), BorderLayout.CENTER );
    f.pack();
    f.setLocationByPlatform(true);
    f.setVisible(true);
    SwingUtilities.invokeLater(r);
    class MainGui extends JPanel {
    JButton logIn;
    JLabel status;
    JPasswordField passwordField;
    JTextField username;
    JLabel logInLabel;
    JPanel mainPanel;
    JPanel usernamePasswordPanel;
    CardLayout cards;
    MainGui() {
    super.setLayout(new BorderLayout(3,3));
    status = new JLabel("Log-In to proceed");
    add(status, BorderLayout.NORTH);
    mainPanel = new JPanel();
    cards = new CardLayout();
    mainPanel.setLayout(cards);
    usernamePasswordPanel = new JPanel(new GridLayout(2,2,3,3));
    usernamePasswordPanel.add( new JLabel("Username:") );
    username = new JTextField(10);
    usernamePasswordPanel.add( username );
    usernamePasswordPanel.setBorder(new EmptyBorder(25,25,25,25));
    usernamePasswordPanel.add( new JLabel("Password:") );
    passwordField = new JPasswordField(10);
    usernamePasswordPanel.add( passwordField );
    logInLabel = new JLabel("Log In to use the app.");
    mainPanel.add(logInLabel,"login");
    JPanel mainApp = new JPanel(new BorderLayout(3,3));
    mainApp.add(new JScrollPane(new JTree()), BorderLayout.WEST);
    mainApp.add(new JTextArea(4,20), BorderLayout.CENTER);
    mainPanel.add(mainApp, "app");
    logIn = new JButton("Log In");
    logIn.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae) {
    if (logIn.getText().equals("Log In")) {
    JOptionPane.showMessageDialog(
    logIn,
    usernamePasswordPanel,
    "Log-In (Pswd hint: any 4+ letters or digits)",
    JOptionPane.QUESTION_MESSAGE);
    checkPassWord();
    } else {
    logOut();
    add(logIn, BorderLayout.SOUTH);
    add(mainPanel, BorderLayout.CENTER);
    setBorder(new EmptyBorder(4,4,4,4));
    public void checkPassWord() {
    // change this for server based authentication
    if (passwordField.getPassword().length>3) {
    cards.show(mainPanel, "app");
    logIn.setText("Log Out");
    status.setText("Logged in as " + username.getText());
    } else {
    status.setText("Log In failed!");
    public void logOut() {
    cards.show(mainPanel, "login");
    logIn.setText("Log In");
    status.setText("Logged out");
    passwordField.setText("");
    related html::
    <html>
    <head></head>
    <body>
    <applet code="LoginApplet2.class" width=300 height=300>
    </applet>
    </body>
    </html>

    >
    I m taking this code from else where . ..>Where? If it is available on the net, it is better to give the URL.
    And whenever pasting code, code snippets, HTML/XML or input/output, please use the code tags. The code tags help preserve the indentation and formatting of the text. To use the code tags, select the text and click the CODE button on the Plain Text tab of the message posting form.(1)
    >
    .. but in o/p after login if u see on right side i get jtree-color-sports-food--like this menu.>Please spell words fully(2). For the sake of saving typing a couple of letters, it makes people seem like buffoons.
    >
    ...If i want my own menu how can i do this ,if any one have idea pls post me to [email protected] or post here >
    - (2) Those words are 'please' and 'you'.
    - The word I should always be upper case. Always.
    - Please add 2 spaces and a single upper case letter at the start of every sentence. This helps the reader, and you would not want to make it harder for people to help you, would you?
    - "If i want my own menu how can i do this" is a question, and should be 'marked' as a question with a question mark -> "If I want my own menu how can I do this?".
    - And since it came up - 'doubt' seems to be an Indian(/English) word for 'question'. These are international forums, so that subject should be 'applet question'
    - It is not a good idea to invite people on public forums to tutor you privately. It is generally felt that public forums are also to help people 'searching' for the answer later, and if a thread goes to email, that opportunity is lost.
    - Posting an email address to a public forum will attract a torrent of spam.
    But the 'short answer' to your question is..
    >
    java code:
    mainApp.add(new JScrollPane(new JTree()), BorderLayout.WEST);>..Use one of the [JTree constructors|http://java.sun.com/javase/6/docs/api/javax/swing/JTree.html#constructor_summary] *(<- link)* that accepts an argument. For further details, see [How to Use Trees|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html] *(<- link)* in the Java Tutorial.
    (1) And here is how that snippet looks when inside code tags
        mainApp.add(new JScrollPane(new JTree()), BorderLayout.WEST);
    ...

  • Exist a Jtree node.id or something like this ?

    I would want to retrieve a node using a unique 'id', for example the absolute index (into the total nodes count)
    Is there something like this ?
    Can I add a particular property to a node ? ( for example this 'id' if it does not exist )
    Another question :
    If I want to implement a search code, this 'id' can be useful, or must I transverse the whole Jtree
    Thanks

    Hello.
    Do the following:
    1. Go to the Apple Menu at the top left of the screen
    2. Select Software Update...
    3. Install any updates that are found.
    If the Amazon issue continues after these updates, then do this:
    1. Open Safari
    2. Erase any web address you have currently showing (for example www.apple.com or www.google.com)
    3. Type in www.amazon.com
    4. That should take you directly to amazon.com
    It should look like this in your Safari::

  • Problem with JTree and memory usage

    I have problem with the JTree when memory usage is over the phisical memory( I have 512MB).
    I use JTree to display very large data about structure organization of big company. It is working fine until memory usage is over the phisical memory - then some of nodes are not visible.
    I hope somebody has an idea about this problem.

    55%, it's still 1.6Gb....there shouldn't be a problem scanning something that it says will take up 300Mb, then actually only takes up 70Mb.
    And not wrong, it obviously isn't releasing the memory when other applications need it because it doesn't, I have to close PS before it will release it. Yes, it probably is supposed to release it, but it isn't.
    Thank you for your answer (even if it did appear to me to be a bit rude/shouty, perhaps something more polite than "Wrong!" next time) but I'm sitting at my computer, and I can see what is using how much memory and when, you can't.

Maybe you are looking for

  • IPhone6 won't pair with BlueTooth on MBPro

    IPhone6, iOS 8.1.1 won't pair with BlueTooth on MBPro nor can I use it as Blue Tooth "hands free" device in my car. Blue Tooth is enabled on the phone and on the MBPro.  I try to "connect to network" on the iPhone, using BT preferences on the MBPro,

  • Parallel port switcher

    Hi all, I have attached a parallel port switcher that I downloaded but I keep getting the error "manager call not supported" as attached. How can I run/ use the attached vi? I have Labview 7 and Labview 8.5 installed, in my Windows XP and Windows 200

  • Split SNP PDS using BADI /SAPAPO/CURTO_SNP Method CIF_IMPORT

    Hello APO ABAP experts, The requirement is to split SNP PDS based on the number of modes. Meaning, the PDS should have only Mode per Activity in the Operations. My plan was to change the changing internal tables in the method CIF_IMPORT to create num

  • Emulator suddenly stopped working

    Hi, recently I have encountered problem with emulator suddenly stopped working. I am using linux (Mandriva 2009.1), WTK 2.5.2_01 and Eclipse 3.5. The only thing I am getting is message "Running with storage root ~/j2mewtk/2.5.2/appdb/temp.DefaultColo

  • Skype 7.0 crashing on startup. began today 12/20/1...

    hey there, just as the topic says, i'm running win7 64, and skype crashes every time I start it, and people wonder why I turn off auto update on most programs... but yeah, i've tried all typical fixes. uninstall/reinstall etc. nothing. it just launch