Simple JTree problem

Hi,
I am new to swings .. so this might be a dumb problem for you UI experts.
I have a JTree using a custom TreeRenderer. Now the getTreeCellRendererComponent() of the custom TreeRenderer is called every time the tree is clicked. I have some icons in the tree that I dynamically load / change in this method. I want the same thing to happen every second (without clicks).
So, I wrote an inner thread, and the run method is like this:
          Thread refresher = new Thread() {
               public void run() {
                    try {
                         Thread.sleep(1000);
                    } catch (InterruptedException e) {
                         e.printStackTrace();
// What shall I call here? tree.repaint() ?
The problem is that I don't know what do I need to call at the place where I've put the comment so that the getTreeCellRendererComponent() is called for all tree components just as it is called on clicks.

It may have done the trick, but it's the wrong solution. As dkrukovsky said, you
should be invoking nodeChanged() when you change a node, including
the icon. That will handle the repaint for you, ensure internal consistency
of the tree, and get rid of your totally unnecessary Thread.

Similar Messages

  • Real simple xslt problem/question

    Hi, i have a real simple xslt problem but i just cant figure out how to do it by looking at various examples on the net. i have a xml document and in it are some elements with a "result" tag name. i want to use xslt to reproduce exactly the same xml document except with an attribute called "id" added to those elements with a "result" tag name. i'm sure that theres a simple solution to it but i just cant figure it out. any helps greatly appreciated, thanks

    Start with the XSLT identity transform (I don't have it handy and it's fairly long, but you should be able to google it up). Add this:<xsl:template match="result">
      <result id="">
        <xsl:apply-templates>
      </result>
    </xsl:template>

  • JDeveloper IDE simple setting problem

    Hi,
    Recently we switched to JDeveloper from Visual Cafe .I have a simple setting problem.How can I set the options so that IDE gives, the core java classes and packages,and our application classes and packeges, prompts in imports as well as in code.Where to set the options.
    eg: when I write
    import java. it should prompt all the pakages.
    Thanks in advance.
    -Gopal
    null

    I am not sure I understand what you are requesting, but ...
    You can configure JDeveloper projects to include various libraries by default.
    This is done by selecting menu Tools | Default Project Properties.../ Libraries tab.
    You should define a library for your classes.
    You can import any of the packages / classes from all the libraries which your project includes.
    It would be incorrect for a tool to automatically add a bunch of import lines at the top of every file because each file should import what it needs and just as importantly, not import what it does not need depending on the component type (e.g. a servlet should not include javax.swing.* ).
    An easy way to import elements into JDeveloper is to type in something like:
    import java.
    // and then type in Ctrl Space
    and this launches the package browser, you can select packages or classes to import.
    You can also do this at the variable declaratiton point such as typing in:
    foo() {
    Frame x
    // Press Control Alt Space
    and this will correctly change the type (Frame) to the type you select in the package browser and add the import statement.
    -John
    null

  • Simple OOP Problem. Help!

    This is just a simple OOP problem that i cant decide on a best
    implementation for.
    im passing an object to an instance of, 'TabbedFrame', which is just
    a frame with a Tabbed Pane in it that is holding custom panels.
    however, these custom panels need access to the object being
    passed to 'TabbedFrame' and to some methods in it.
    i cant make them static however so how do i gain access to them?
    is my only option to pass the 'TabbedFrame' to each panel?
    like - jtabbedpane.add( "Panel 1", new mypanel1(this));
    here is code:
    new TabbedFrame( DataObject );
    public class TabbedFrame{
    public TabbedFrame(DataObject do){
    this.do = do;
    jtabbedpane.add( "Panel 1", new mypanel1() );
    DataObject do;
    public class mypanel1{
    public mypanel1(){
    // need access to DataObject of the 'TabbedFrame' object that instantiated
    // this 'mypanel1' and to some of its methods
    }i would just pass the DataObject to evey panel (there are 12) but
    i also need to be able to call methods in the 'TabbedFrame'.
    Any help would be appreciated!

    Modify mypanel1's constructor:
    public class mypanel1{
    TabbedFrame tf;
    public mypanel1(TabbedFrame tf){
    this.tf = tf;
    // need access to DataObject of the 'TabbedFrame' object that instantiated
    // this 'mypanel1' and to some of its methods
    DataObject theDo = tf.getDataObject();
    tf.someMethod(); // Call method on the TabbedFrame
    }In TabbedFrame:
    public TabbedFrame(DataObject do){
    this.do = do;
    // Modify call to constructor to pass "this" TabbedFrame.
    jtabbedpane.add( "Panel 1", new mypanel1(this) );
    }

  • Any component as leaf for JTree problems

    hi,
    I'm trying to get arbitary components as leaves in a JTree and it looks like its very nearly there, but there are two (related?) problems.
    1) If you click around on the top 3 tree components then it gets stuck in a loop of rendering and causes a stack exception to be thrown.
    2) For the embedded JTree component, expanding its nodes doesn't update the parent tree
    both may be because current the row height is set at the wrong time (in the TreeCellRenderer)
    any help would be really appreciated!
    thanks,
    asjf
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    import java.util.*;
    public class ComponentTree
         public static void main(String args[])
              try{(new UIManager()).setLookAndFeel((new UIManager()).getSystemLookAndFeelClassName());}
              catch(Exception e){}
              DefaultMutableTreeNode c0 = new DefaultMutableTreeNode(new JButton("root"));
              DefaultMutableTreeNode c1 = new DefaultMutableTreeNode(new JButton("c1"));
              DefaultMutableTreeNode c2 = new DefaultMutableTreeNode(new JList(new Object [] {"A","B","C"}));
              DefaultMutableTreeNode c3 = new DefaultMutableTreeNode(new JTable(new Object [][] {{"Active","true"},{"User","root"}}, new Object [] {"Name","Value"}));
              DefaultMutableTreeNode c4 = new DefaultMutableTreeNode(new JTree());
              DefaultMutableTreeNode c5 = new DefaultMutableTreeNode(new JList(new Object [] {"D","E","F"}));
              DefaultMutableTreeNode c6 = new DefaultMutableTreeNode(new JCheckBox("Active",true));
              DefaultTreeModel dtm = new DefaultTreeModel(c0);
                   dtm.insertNodeInto(c6,c0,0);
                   dtm.insertNodeInto(c1,c0,0);
                   dtm.insertNodeInto(c2,c0,0);
                   dtm.insertNodeInto(c5,c2,0);
                   dtm.insertNodeInto(c3,c1,0);
                   dtm.insertNodeInto(c4,c3,0);
              JTree tree = new JTree(dtm);
                   tree.setEditable(true);
                   tree.setCellRenderer(new DefaultTreeCellRenderer()
                        public Component getTreeCellRendererComponent(     JTree tree,     Object value, boolean isSelected, boolean expanded, boolean leaf, int row, boolean hasFocus)
                             System.out.println("Render row "+row);
                             Component c = (Component) ((DefaultMutableTreeNode) value).getUserObject();
                             if(c instanceof JCheckBox)
                                  c.setBackground(UIManager.getColor("Tree.textBackground"));
                             tree.setRowHeight(c.getHeight());                    
                             return c;     
                   tree.setCellEditor(new DefaultTreeCellEditor(tree,(DefaultTreeCellRenderer)tree.getCellRenderer())
                        public boolean isCellEditable(EventObject evt){return true;}
                        public Component getTreeCellEditorComponent(     JTree tree,     Object value, boolean isSelected, boolean expanded, boolean leaf, int row)
                             return (Component) ((DefaultMutableTreeNode) value).getUserObject();
              JFrame frame = new JFrame("ComponentTree");
                   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frame.getContentPane().add(tree);     
                   frame.pack();
                   frame.show();
    }

    thanks!
    this seems an awful lot of code to get this working - it should be possible to have a single CellEditor/Renderer??
    also running the code - its very hard to select checkbox items, and the JLists seem to disable themselves when the main tree updates?
    its also not general to any Component (?) (although we probably only want JComponent) so we can't add a JTree as a leaf?
    I'm guessing there is a simpler way to get this working?

  • Simple button problem

    I am having a real problem creating a simple button - I have
    created a Flash file using Action script 2, and when I create a
    simple button - text with a rectangle as a background, (see
    http://www.elkhavenestate.com),
    and the over state is behaving in a bizarre fashion. This is my
    first time using CS3, so is there a new control that I'm
    missing?

    I take it that it's the Home button. It appears to have a
    selectable text field or something in it, which is causing the
    problem. Either change that to a static text field or set its
    selectable property to false. The other two buttons appear to be
    fine, so maybe you can just duplicate one of them and turn it into
    the Home button.
    If I picked the wrong button, let me know.

  • An Expandable JTree Problem

    Hi, I'm relatively new to creating JTree components, now I have looked at many examples, and this one is nearest (i can see) to how I want my Jtree to look, however it doesn't behave in a way which I would like!
    Firstly, I can set the root node to have as many folders as i want, however they only mirror whats in the first root node, I dont want this - I want to be able to create about 5/6 different roots that will yield different results - I also want after each time you click on a folder, which will ask a question about a patient i.e. "Has the patient a head injury" - click on this then it should come up with "3" more different choices, so altogther want it about 5 deep.
    However, this is what I've got so far - but like I say, its not yielding the results I want, does anyone know how to modify this or can anyone point me in the right direction by starting me off a bit, that would be great!
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    public class SelectableTree extends JFrame
                                implements TreeSelectionListener {
      public static void main(String[] args) {
        new SelectableTree();
      private JTree tree;
      private JTextField currentSelectionField;
      public SelectableTree() {
        super("Clinical Information Help System");
        WindowUtilities.setNativeLookAndFeel();
        addWindowListener(new ExitListener());
        Container content = getContentPane();
        DefaultMutableTreeNode root =
          new DefaultMutableTreeNode("Begin Clinical Questions");
        DefaultMutableTreeNode child = null;
        DefaultMutableTreeNode parent = null;
        DefaultMutableTreeNode grandChild = null;
        DefaultMutableTreeNode grandParent = null;
        DefaultMutableTreeNode child2 = null;
        DefaultMutableTreeNode parents = null;
        for(int grandParentIndex=1; grandParentIndex < 2; grandParentIndex++) {
          grandParent = new DefaultMutableTreeNode("[Does Patient Have Back Pains?] " + grandParentIndex);
          root.add(grandParent);
          for(int parentIndex =1; parentIndex < 3; parentIndex++) {
            parent = new DefaultMutableTreeNode("[Does the patient also have leg pain?] " + parentIndex +
                                         "." + parentIndex);
            grandParent.add(parent);
            for(int childIndex =1; childIndex < 3; childIndex++) {
             child = new DefaultMutableTreeNode("[are the pains in the lower back?] " + childIndex +
                                         "." + childIndex);
              parent.add(child);
              child2 = new DefaultMutableTreeNode("patient over 60?" + childIndex +
                    "." + childIndex);
              child.add(child2);
            for(int grandChildIndex =1; grandChildIndex < 3; grandChildIndex++) {
               grandChild = new DefaultMutableTreeNode("[Does patient have bladder and/or bowel incontinence?] " + grandChildIndex +
                                            "." + grandChildIndex);
                 child.add(grandChild);
            for(int childIndex = 1; childIndex < 3; childIndex++) {
                child = new DefaultMutableTreeNode("[Has Patient suffered either: appitite/wieght loss/fever?]" + childIndex +
                                             "." + childIndex);
                child = new DefaultMutableTreeNode("[Has pain been 4-6wks leg pain? OR 3-6mths low-back pain?]" + childIndex +
                        "." + childIndex);
                  grandChild.add(child);
        tree = new JTree(root);
        //tree = new JTree(root2);
        tree.addTreeSelectionListener(this);
        content.add(new JScrollPane(tree), BorderLayout.CENTER);
        currentSelectionField = new JTextField("Current Selection: NONE");
        content.add(currentSelectionField, BorderLayout.SOUTH);
        setSize(400, 400);
        setVisible(true);
      public void valueChanged(TreeSelectionEvent event) {
        currentSelectionField.setText
          ("Current Selection: " +
           tree.getLastSelectedPathComponent().toString());
    }

    I'm not really sure what your problem is, for I don't see what you mean by "mirror". If it is you have but one root node, but wanted to have many instead, then you'd simply need to call setRootVisible(false); on the tree.
    As a sidenote, I don't think it's a really good UI for what you're doing, but after all, I haven't got the whole picture.
    Now, what is it you mean by: its not yielding the results I want ?

  • JTree problem

    I posted a simillar problem not long ago but didn't explain properly.
    The code below displays a JFrame with a JScrollPane containing a JTree with just a root node ("root").
    At the bottom of the frame is a button that when pressed re-initialises the JTree with no arguments (line 42). Hence once the button is clicked the JTree should have some elements in it (those default ones : colours, sports, food).
    However, the reinitialised JTree is not displayed. What's the problem?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    class Test extends JFrame implements ActionListener {
         private JScrollPane            treeScrollPane;
         private JTree                  tree;
         private DefaultMutableTreeNode root;
         private JButton                runButton;
         public Test() {
              super("Test");
              this.tree = new JTree(this.root = new DefaultMutableTreeNode("root"));
              this.treeScrollPane = new JScrollPane(new JTree());
              this.treeScrollPane.setBorder(BorderFactory.createCompoundBorder(
                   BorderFactory.createTitledBorder("Tree panel"),
                   BorderFactory.createEmptyBorder(5,5,5,5)));
              this.runButton = new JButton("click me");
              this.runButton.addActionListener(this);
              Container contentPane = getContentPane();
              contentPane.setLayout(new BorderLayout());
              contentPane.add(this.treeScrollPane, BorderLayout.CENTER);
              contentPane.add(this.runButton,      BorderLayout.SOUTH);
              this.setSize(300, 400);
              this.setLocationRelativeTo(null);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.setVisible(true);
         public void actionPerformed(ActionEvent e) {
              Object source = e.getSource();
              if (source == this.runButton) {
                   System.out.println("DEBUG : button clicked");
                   this.tree = new JTree();
                   this.tree.expandPath(new TreePath(this.tree.getModel().getRoot()));
         public static void main(String args[]) {
              try {
                   UIManager.setLookAndFeel(
                        UIManager.getSystemLookAndFeelClassName());
              } catch (Exception e) {
                   System.out.println(e.getMessage());
              new Test();
    }

    The problem is that the scrollpane is still displaying the first tree.
    To fix this, you'll need to add the following line to your actionPerformed method:
    treeScrollPane.setViewportView(tree);(I think you might be a litle confused by the difference between an object and a reference. The scrollpane holds a reference to the first tree you create. Then you create a new tree and assign it to your this.tree reference, but the scrollpane's reference is stil pointing to the first tree. If this explanation is all mumbled up it's because I haven't had my first cup of coffee yet :-)

  • JTree - problems with names of elements

    I have a Jtree thats populated with expandable elements. These elements are loaded on startup, but some of the elements don't get their full names, just i.e "dem..." instead of "demo3". WHen I expand the node, the full name appears, and remains.
    Anyone know what this could be?
    The problem is really often associated with nodes with names containing "m" ..

    By default the tree node renderer is JLabel.
    It look like you are not using pack() or validate().
    It depend also the layout manager you are using.
    In one word, it seems the JLabel has dimension too short.
    Can only show 3 to 4 char. that is why "demo3" show as "dem..."
    Try have some node name like "WWWWW", if you see "WW..." or "WWW..."
    Then that is the problem. ( Not as you thought: only "m" has problem )

  • Logo/picture to menubar? simple css problem?

    Hi, I'm having a problem getting a logo to appear correctly in a horizontal menu bar. It appears to be fine in IE 8, Safari 5, Chrome, and Firefox. However in IE 7 and lower it does not seem to display correctly. The only conditional notes I have for IE 7 and lower deals with the slideshow on the page which shouldn't be affecting the menubar as it is in a different div.
    Here is the url: www.elementcentral.com
    Any advice? I could really use some help- I've tried quite a few things but to no avail...
    Thanks for any help you can offer and I'm more than happy to clarify or anything else!
    Sincerely,
    Matt

    Anyone? I'm thinking its just something simple but I can't figure it out for the life of me heh.

  • JTree Problem again

    Deat 7rst,
    Sorry, I want to ask you about the same problem.
    if I want to display a difference components from difference node in JTree, how the code I must use?
    I already understand about the code that you give to me. But I still confuse if many nodes in JTree to perform difference panel with many components each of its. The components beside JTextField.
    Thanks

    I have used THE SEARCH BOX - can't find nothing about editable JList, there are only references for editable Trees and Tables.
    Do anybody have concrete idea (the best would be some code), or should I reconcile myself with the JTable solution?

  • Simple DLL problem

    I'm dabbling with DLL writing and can't figure out how to pass a string to a
    DLL. As far as I can see, it should be simple.
    My DLL function, in the DLL "test.dll", is simply
    TEST_API int test(LPCTSTR WinName)
    return 0;
    Instead of LPCTSTR I've also tried the more conventional "char *WinName",
    and a few others. All give the same error; "The exception Priviledged
    Instruction occurred in the application at location (blah)." The error
    message doesn't seem too specific; exactly the same thing happens if I
    deliberately copy some text to an uninitialised pointer.
    I'm calling the function using a "Call Library Node", passing a
    pre-generated string in the form of a C string pointer. The calling
    convention is set to "winapi" but doesn't seem too relevant.
    If I remove the string argument and change the function definition to take
    (void) then it works, in that I can put integers in the return code and pass
    them back to Labview, so it's the passing of the string that's the problem.
    However, if I have more code in there and I use the Visual C++ debugger, the
    error message is only generated on hitting the "return" line, and I can see
    the string that has been passed in when I look at "WinName" in the debugger.
    Can anyone shed some light on this?
    Craig Graham
    Physicist/Labview Programmer
    Lancaster University, UK

    Craig;
    I am going to throw some random thoughts that may help you in your situation:
    - I avoid to use VC's wizard. It gives (and gave me) a lot of headaches. All it does it to add a lot of garbage to your project that nobody understand.
    - If your source file is a .cpp, wrap your function prototypes inside the extern "C" declaration.
    - Always initialize every variable in LabVIEW side. For example, for your function you should wire an empty string in the input side of the "Call Library Node" for the "WinName" variable.
    - I claim ignorance in this one, but seems to simplify my projects. Exclude rarely-used Windows header files by adding the following statement before your headers "include":
    #define VC_EXTRALEAN
    I hope this can be of help. If I co
    me up with some more suggestion, I'll let you know.
    Best regards;
    Enrique
    www.vartortech.com

  • Another simple classpath problem question

    Hi All
    Yes I know, there are a lots of questions about this matter, but I couldn't found a solution to my problem.
    I have a simple program:
    public class prueba {
            public static void main(String[] args) {
                    System.out.println("Ahi va...");
    }placed in /tmp/javier/prueba.java
    After compiled, I've tried to run it from / and then problems started:
    cd /
    java /tmp/javier/prueba
    Exception in thread "main" java.lang.NoClassDefFoundError: /tmp/javier/prueba (wrong name: prueba)
    I said, ok...it could be a classpath problem...then:
    java -cp /tmp/javier/ /tmp/javier/prueba
    Exception in thread "main" java.lang.NoClassDefFoundError: /tmp/javier/prueba
    Damn, another try...
    java -cp .:/tmp/javier/ /tmp/javier/prueba
    Exception in thread "main" java.lang.NoClassDefFoundError: /tmp/javier/prueba (wrong name: prueba)
    Jesus Christ....may be the last slash....
    java -cp .:/tmp/javier /tmp/javier/prueba
    Exception in thread "main" java.lang.NoClassDefFoundError: /tmp/javier/prueba (wrong name: prueba)
    Oh...no.... may be classpath to java classes..
    java -cp .:/usr/java/j2sdk1.4.2_01/lib/jre/:/tmp/javier/ /tmp/javier/prueba
    Exception in thread "main" java.lang.NoClassDefFoundError: /tmp/javier/prueba (wrong name: prueba)
    Well, I don't know why this error happens....
    Please, could somebody help me !!!
    Thanks in advance...
    <jl>

    It's not too early to start following the Sun coding
    conventions for Java:
    http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.
    tmlHi
    thanks for your reply.
    Yes, I agree. I use conventions with my programs. But my real problem was with a real application and then I did quickly this simple code to help others to understand the problem and give a fast reply...
    Let me know if that works. (It was fine on my
    machine.) - MODYes it works fine, thanks.... and Damn...Murphys law again, the only option I didn't tried is the solution to my problem... :)
    Thanks again...

  • JTree Problem - Need help

    Hi,
    I am using a JTree to which I have set my own TreeModel and TreeSelectionListener (overidden all the methods for both). Wehn I add a new node to the tree, the node appears but the text for the node does not.
    (e.g if the text is "ABCD", what appears is "AB..."). I called a tree.repaint(). It does not solve my problem.
    A tree.updateUI() does solve my problem, but it throws a NullPointerException on every selection in the tree. I am trying to refresh the tree in the selSelection() method of the selection model.
    Is there any other way?
    Thanks in advance,
    Achyuth

    Try adding this when you add a node. Don't have time to check it so not quite sure its what you're looking for but I remember having this prob before and I think this is what I did:
    EventListener[] listeners = ((DefaultTreeModel)tree.getModel()).getListeners(TreeModelListener.class);
    for (int i = 0; i < listeners.length; i++) {
              ((TreeModelListener)listeners).treeNodesChanged(new TreeModelEvent(this, new TreePath(node.getPath())));
    Alex

  • Simple Form Problem: Cant press Enter in form without getting error message: Invalid Input

    The problem is very simple,
    I have several forms on my site such as the 'quick enquiry'
    form on the home page about half way down.
    http://www.party-invitation.co.uk/index.htm
    The user enters name- Works Fine
    user enters email address- Works Fine
    User enters a question- This is were the problem occurs when
    the users presses the Enter key. This seems to bring up a message
    that says Invalid Input.
    Does anyone know how i can allow people to use the Enter key
    in my forms to skip lines without causing this error message?
    Any help would be appreciated.
    Feel free to use the form to test it out.
    Thanks.
    Here is my php code for the form.
    <?
    function checkOK($field)
    if (eregi("\r",$field) || eregi("\n",$field)){
    die("Invalid Input!");
    $Name=$_POST['Name'];
    checkOK($Name);
    $Email=$_POST['Email'];
    checkOK($Email);
    $Question=$_POST['Question'];
    checkOK($Question);
    $to="[email protected]";
    $message="
    A Quick Enquiry has been submitted from
    www.Party-Invitation.co.uk
    Here are the details:
    Name: $Name
    Email: $Email
    Question: $Question
    if(mail($to,"Quick Enquiry: $Email $Name" ,$message,"From:
    $email\n")) {
    echo "";
    } else {
    echo; "There was a problem sending the mail. Please check
    that you filled in the form correctly.";
    ?>

    .oO(stuckinthesystem)
    > Here is my php code for the form.
    > <?
    This should be <?php for portability reasons. Short open
    tags are an
    optional feature and can be disabled.
    > function checkOK($field)
    > {
    > if (eregi("\r",$field) || eregi("\n",$field)){
    The old ereg_* functions should not be used anymore. Better
    would be
    something like
    if (preg_match("/[\n\r]/", $field)) {...}
    > $Name=$_POST['Name'];
    > checkOK($Name);
    > $Email=$_POST['Email'];
    > checkOK($Email);
    > $Question=$_POST['Question'];
    > checkOK($Question);
    The last check causes the error if the user enters multiple
    lines in the
    text area. You can remove that check, because line breaks in
    the email
    body are safe.
    > if(mail($to,"Quick Enquiry: $Email $Name"
    ,$message,"From: $email\n")) {
    > echo "";
    There's a typo in the last parameter. Variable names in PHP
    are
    case-sensitive, so $Email != $email. You should set
    error_reporting to
    E_ALL in your php.ini, so PHP will let you know about such
    errors.
    Micha

Maybe you are looking for