JEditorPane and JTree

Hi,
I have a tree that lists all objects and I want to do some kind of search feature. Results would be displayed in JEditorPane but I don't know anything about that. In JTree there is TreeSelectionListener (method valueChanged) and that has the functionality I need to have on JEditorPane but I don't know if this is possible?
Any advices please?

Hi,
I have a tree that lists all objects and I want to do some kind of search feature. Results would be displayed in JEditorPane but I don't know anything about that. In JTree there is TreeSelectionListener (method valueChanged) and that has the functionality I need to have on JEditorPane but I don't know if this is possible?
Any advices please?

Similar Messages

  • How to load a text file int JEditorPane and highlight some words (Urgent !)

    I want to load a text file into a JEditorPane and then highlights some keywords such as while,if and else.I am using an EditorKit in order to style the JEditorPane. I have no difficulty while giving the input through the keyboard but lots of exceptions are thrown if i try to load the string from a file.

    Hi,
    I think the setCharacterAttributes(int offset, int length, AttributeSet s, boolean replace) will solve the problem.
    You can create your own Styled Document and set it to the Editor Pane.

  • Apply formatting in a JEditorPane and export the content in HTML.

    Hi,
    I'm writing, a program to allow the user to enter a formated text and even add images in a JEditorPane.
    Here is a simple sample of the code:
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;              //for layout managers and more
    import java.awt.event.*;        //for action events
    import java.net.URL;
    import java.io.IOException;
    public class EditorPane extends JPanel{
        private String newline = "\n";
        private JPanel buttonPanel;
        private JPanel textPanePanel;
        private JEditorPane myEditorPane;
        private JButton boldButton;
        private JButton colorButton;
        private JButton imgButton;
        private JButton saveButton;
         public EditorPane() {
            createGUI();
        private void createGUI() {
            buttonPanel = new JPanel();
            boldButton = new JButton("Bold");
            boldButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    boldButtonActionPerformed(evt);
            colorButton = new JButton("Color");
            colorButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    colorButtonActionPerformed(evt);
            imgButton = new JButton("Image");
            imgButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    imgButtonActionPerformed(evt);
            saveButton = new JButton("Save");
            saveButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    saveButtonActionPerformed(evt);
            buttonPanel.setLayout(new GridLayout(1, 4));
            buttonPanel.add(boldButton);
            buttonPanel.add(colorButton);
            buttonPanel.add(imgButton);
            buttonPanel.add(saveButton);
            textPanePanel = new JPanel();
            textPanePanel.setLayout(new BorderLayout());       
            myEditorPane = this.createEditorPane();
            JScrollPane paneScrollPane = new JScrollPane(myEditorPane);
            textPanePanel.add(paneScrollPane, BorderLayout.CENTER);
            this.setLayout(new BorderLayout());
            this.add(buttonPanel, BorderLayout.NORTH);
            this.add(textPanePanel, BorderLayout.CENTER);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                     JFrame frame = new JFrame("TextSamplerDemo");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   EditorPane newContentPane = new EditorPane();
                    //newContentPane.setOpaque(true); //content panes must be opaque
                    frame.setContentPane(newContentPane);
                    frame.pack();
                    frame.setSize(300,300);
                    frame.setVisible(true);
    private JEditorPane createEditorPane() {
            JEditorPane editorPane = new JEditorPane();
            editorPane.setEditable(true);
            java.net.URL helpURL = TextSamplerDemo.class.getResource(
                                            "simpleHTMLPage.html");
            if (helpURL != null) {
                try {
                    editorPane.setPage(helpURL);
                } catch (IOException e) {
                    System.err.println("Attempted to read a bad URL: " + helpURL);
            } else {
                System.err.println("Couldn't find file: simpleHTMLPage.html");
            return editorPane;
        private void boldButtonActionPerformed(java.awt.event.ActionEvent evt) {
        System.out.println("boldButtonNextActionPerformed");
        //myEditorPane
            // TODO add your handling code here:
        private void colorButtonActionPerformed(java.awt.event.ActionEvent evt) {
        System.out.println("colorButtonActionPerformed");
            // TODO add your handling code here:
        private void imgButtonActionPerformed(java.awt.event.ActionEvent evt) {
        System.out.println("imgButtonActionPerformed");
            // TODO add your handling code here:
        private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {
        System.out.println("saveButtonActionPerformed");
        String newStr = new String("this is the new String");
        //newStr.setFont(new java.awt.Font("Tahoma", 0, 14));
        this.myEditorPane.replaceSelection("sdfsdfsd");
            // TODO add your handling code here:
    }and the HTML Code of simpleHTMLPage.html is
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <title>Untitled Document</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>
    <body>
    <p>Simple text</p>
    <p><strong>Bold text</strong></p>
    <p><em>Italic text</em></p>
    <p align="center">Center text</p>
    <p><font color="#000099"><strong>Color text</strong></font></p>
    <p>image here : <img src="images/Pig.gif" width="121" height="129"></p>
    <p> </p>
    </body>
    </html>By pressing the Save button I can change the selected text.
    I don�t know the way to get and apply the format (size, color �) to only the selected text and display the selected image in real time in the EditorPane. Like if you press the Bold button, the selected text font will be change to bold.
    I would like to get or save the HTML code of the content of the EditorPane by pressing the Save button, How to make it?
    I can apply the formatting on the selected text in a JTextPane, but I don't know the way to save or export the content in HTML. By doing that it could fix my problem too.
    So any help to do that will be much appreciated.
    Thanks.

    Hi,
    Tks for your answer. That one I can do it. I would like to display the selected text in bold instead of adding the tag in the JEditorPane. If I get you right, you get the hole content of the JEditorPane and save it. How did you get it ? And before saving that in the database, did you fing the keysWord to convert the HTML tag in the corresponding entities ?
    Bellow you have a sample of code to make the formatting in the JTextPane.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    import javax.swing.text.Highlighter;
    import javax.swing.event.*;
    import java.util.*;
    import javax.swing.text.*;
    import javax.swing.text.BadLocationException;
    public class MonJTextPane extends JFrame implements CaretListener, ActionListener
              *     Attributs :
         private JTextPane monTextPane;
         private JLabel monLabel;
         private JButton monBouton;
         private StyleAide style; // class qui defini les effets de style de l'editeur
              *     Constructeur :
         public MonJTextPane ()
         {     super ("Aide");
              // construction du composant Texte
              this.style = new StyleAide (new StyleContext ());
              this.monTextPane = new JTextPane ();
              this.monTextPane.setDocument (style);
              this.monTextPane.addCaretListener (this);
              // construction de la fenetre :
              this.getContentPane ().setLayout (new BorderLayout ());
              this.setBounds (150,150,600,550);
              this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              this.monLabel = new JLabel ("Auncune ligne saisie...");
              this.monBouton = new JButton ("change de style");
              this.monBouton.addActionListener (this);
              JPanel panel = new JPanel ();
              panel.setLayout (new GridLayout (1,2));
              panel.add (monLabel);
              panel.add (monBouton);
              this.getContentPane ().add (panel, BorderLayout.SOUTH);
              this.getContentPane ().add (this.monTextPane, BorderLayout.CENTER);
              this.setVisible (true);
              *     Methodes :
         private int getCurrentLigne ()
         {     return ( this.style.getNumLigne (monTextPane.getCaretPosition ())+1 );
         public int getCurrentColonne ()
         {     return ( this.style.getNumColonne (monTextPane.getCaretPosition ())+1 );
              *     Methodes CaretListener:
         // ecoute les deplacements du curseur d'insertion
         public void caretUpdate(CaretEvent e)
         {     int debut = java.lang.Math.min (e.getDot (), e.getMark ());
              int fin   = java.lang.Math.max (e.getDot (), e.getMark ());
              this.monLabel.setText ("Ligne numero : "+ this.getCurrentLigne ()+" Colonne : "+this.getCurrentColonne ()+" (debut : "+debut+", fin : "+fin+")");
              *     Methodes ActionListener:
         public void actionPerformed (ActionEvent e)
         {     int start     = monTextPane.getSelectionStart();
              int end          = monTextPane.getSelectionEnd();
              int debut     = java.lang.Math.min (start, end);
              int fin          = java.lang.Math.max (start, end);
              int longueur= fin - debut;
              this.style.changeStyleSurligne (debut, longueur);
         // lance le tout ....
         public static void main (String argv [])
         {     new MonJTextPane ();
    // la Classe DefaultStyledDocument correspond a la classe utilise comme Model pour les
    // composant Texte evolue comme : JTextPane ou JEditorPane
    // en derivant de cette derniere nous pouvons donc redefinir les methodes d'insertion afin de personnalise
    // le style d'ecriture en fonction du texte et creer une methode permettant de modifier le style utilise pour
    // une partie de texte deja ecrite.
    class StyleAide extends DefaultStyledDocument
              *     Constructeur :
         public StyleAide (StyleContext styles)
         {     super (styles);
              initStyle (styles);
              *     Methodes :
         // redefini pour choisir l'effet de style a utiliser
         public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
         {     try
              {     // si le texte insere est egale a HELP le texte s'ecrit avec le style "styleOp"
                   if ( str.equals ("HELP") )
                   {     super.insertString (offs, str, getStyle ("styleOp"));
                   else // sinon le texte est ecrit avec le style "styleNormal"
                   {     super.insertString (offs, str, getStyle ("styleNormal"));
              catch (BadLocationException e)
              {     System.out.println ("Tuuuttt erreur Insere");
         // modifie le style d'ecriture d'un texte deja ecrit compris
         public void changeStyleSurligne (int positionDepart, int longueur)
         {     setCharacterAttributes (positionDepart, longueur, getStyle ("styleKeyWord"), true);
         // le Model d'un composant texte est enregistre sous form d'un arbre
         // cette methode permet de recuperer le noeud root de l'arbre
         private Element getRootElement ()
         {     return this.getDefaultRootElement ();
         // methode permettant d'obtenir la ligne correspondant a un offset donnee
         public int getNumLigne (int offset)
         {     Element eltR = getRootElement ();
              int numLigne = eltR.getElementIndex (offset);
              Element elt  = eltR.getElement (numLigne);
              if ( offset != elt.getEndOffset () )
              {     return numLigne;
              else
              {     if ( numLigne != 0 )
                   {     return numLigne+1;
              return 0;
         public int getNumColonne (int offset)
         {     Element eltR = getRootElement ();
              Element elt = eltR.getElement (eltR.getElementIndex (offset));
              int numColonne = offset-elt.getStartOffset ();
              return numColonne;
         // Defini les differents styles
         private static void initStyle (StyleContext styles)
         {     // definition du style pour le texte normal (brute)
              javax.swing.text.Style defaut = styles.getStyle (StyleContext.DEFAULT_STYLE);
              javax.swing.text.Style styleNormal = styles.addStyle("styleNormal", defaut);
              StyleConstants.setFontFamily (styleNormal, "Courier");
              StyleConstants.setFontSize (styleNormal, 11);
              StyleConstants.setForeground(styleNormal, Color.black);
              javax.swing.text.Style tmp = styles.addStyle("styleKeyWord", styleNormal);
              // Ajout de la couleur blue et du style gras pour les mots cle
              StyleConstants.setForeground(tmp, Color.blue);
              StyleConstants.setBold(tmp, true);
              tmp = styles.addStyle("styleOp", styleNormal);
              // Ajout de la couleur rouge pour le style des operateurs
              StyleConstants.setForeground(tmp, Color.red);
    }But it hard for me to convert it in the corresponding HTML document.
    Did you have and idea
    Tkks

  • JEditorPane and HTML Coded Character Set

    Hi.
    How to prevent JEditorPane to convert its content into HTML coded character set (like
    &#1072;&#1073;&#1074;&#1075;&#1076;&#1077;&#1105;&#1078;
    I would like to receive normal unicode string from getText() method.
    Setting content type
    editorPane.setContentType("text/html; charset=ISO-10646");
    has no effect.

    you would have to iterate through the elements of the HTMLDocument in the JEditorPane and look for the HTML tags you are interested in. Once a tag is found its AttributeSet will have the content. I am too lazy to post how it is done again. There are tons of postings in the forum about the topic, so by simply using the search function you should find respective hints.

  • Consume MouseEvent to prevent JList and JTree from receiving?!

    I have a JTree and a JList where I have made the CellRenderer so that it has a "button" area. When this button is clicked, I want something to happen. This I have achieved just nicely with a MouseListener, as per suggestion from JavaDocs.
    However, the problem is that when a click is deemed to be within the "button", I do not want the tree or list to process it anymore. But doing e.consume(), both on mousePressed or mouseClicked (though it obviously is pressed the JList and JTree themselves listen to) doesn't do jack.
    How can I achieve this functionality?

    da.futt wrote:
    stolsvik wrote:
    Okay, I managed with a hack: It is the order of listeners that's the problem: The ListUI's MouseListener is installed before mine, and hence will get the MouseEvent before me, so it has already processed it when I get it, and hence consuming it makes no difference. No. Normally, listeners are notified latest-registered to earliest-registered. I don't remember seeing an exception to that rule in the core API. well, you are both right (or wrong ;-) - the rule is: the order of listener notification is undefined, it's an implementation detail which listeners must not rely on. "Anecdotical" experience is that AWTListeners are notified first-registered-first-served, while listeners to swing specific events are notified last-registered-first-served. Below is a snippet (formulated in context of SwingX convenience classes, too lazy ...) showing that difference.
    The latter probably stems from hefty c&p of notification by walking the EventListenerList: the earliest code was implemented very near the beginning of Swing when every little drop of assumed performance optimization was squeezed, such as walking from back to front. Using EventListenerList involves lots of code duplication ... so lazy devs as we all are, simply c&p'ed that loop and just changed the concrete event type and method name. More recently, as in the we-use-all-those-nifty-cool-language-features ;-) I've seen more usage of forEach loops (f.i. in beansbinding) so notification is back to first-in-first-served :-)
    Bottom line: don't rely on any sequence - if needed, use an eventBus (or proxy or however it's called) and define the order there. Darryl's suggestion is as close as we can get in Swing (as it's not supported) but not entirely safe: there's no way to get notified when listeners are added/removed and no hook where to plug-in such a bus into the ui-delegate where it would belong.
    Cheers
    Jeanette
    // output
    02.10.2009 14:21:57 org.jdesktop.swingx.event.EventOrderCheck$1 mousePressed
    INFO: first added mouseListener
    02.10.2009 14:21:57 org.jdesktop.swingx.event.EventOrderCheck$2 mousePressed
    INFO: second added mouseListener
    02.10.2009 14:21:58 org.jdesktop.swingx.event.EventOrderCheck$4 valueChanged
    INFO: second added listSelectionListener
    02.10.2009 14:21:58 org.jdesktop.swingx.event.EventOrderCheck$3 valueChanged
    INFO: first added listSelectionListener
    // produced by
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.util.logging.Logger;
    import javax.swing.JList;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import org.jdesktop.swingx.InteractiveTestCase;
    import org.jdesktop.test.AncientSwingTeam;
    public class EventOrderCheck extends InteractiveTestCase {
        public void interactiveOrderAWTEvent() {
            JList list = new JList(AncientSwingTeam.createNamedColorListModel());
            MouseListener first = new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    LOG.info("first added mouseListener");
            MouseListener second = new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    LOG.info("second added mouseListener");
            list.addMouseListener(first);
            list.addMouseListener(second);
            ListSelectionListener firstSelection = new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (e.getValueIsAdjusting()) return;
                    LOG.info("first added listSelectionListener");
            ListSelectionListener secondSelection = new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (e.getValueIsAdjusting()) return;
                    LOG.info("second added listSelectionListener");
            list.addListSelectionListener(firstSelection);
            list.addListSelectionListener(secondSelection);
            showWithScrollingInFrame(list, "event order");
        @SuppressWarnings("unused")
        private static final Logger LOG = Logger.getLogger(EventOrderCheck.class
                .getName());
        public static void main(String[] args) {
            EventOrderCheck test = new EventOrderCheck();
            try {
                test.runInteractiveTests();
            } catch (Exception e) {
                e.printStackTrace();
    }

  • Whats the difference between JEditorPane and JTextPan

    I was wondering where to use which? It looks like they have the same features, except that JEditorPane can load text from a URL.

    Hi,
    ofcourse it can, it is a subclass of JEditorPane and inherits its functionality :)
    greetings Marsian

  • Xml to JTree, and JTree node to html file.

    I have been trying to figure out a way to do this and I think I have a solution, but I am not sure how to structure the application and methods.
    working with BorderLayout Panel p, JSplitPane split, JTree tree, and JEditorPane rpane
    1st. My JSplitpane is divided with the tree, and rpane. The tree is on the left, and the rpane is on the right. both of these are then added to the Panel p
    2. I will create a method that will read through a modules.xml file, and create a JTree - tree. When you click on the node element it's information is displayed in the right pane - rpane.
    The Problem. I think it would take to long to create the html file on the fly each when I click on each individual node.
    So my idea is to create the html files from many xml files when I run the program. I can then just load the html file when I click on each individual node.
    This means alot of heavy processing in the front end, and everything will be static, but it will be faster when the user is in the program.
    Problem. How do I associate each node element with the correct html file?
    The Tree elements are always the same, but I can have 1 or many modules.
    Here is an example:
    <device>  // - root
       <module1>
          <Status>
             <Network></Network>
             <Device></Device>
             <Chassis></Chassis>
             <Resources></Resources>
          </Status>
          <ProjMngt></ProjMngt>
          <ProjEdit></ProjEdit>
          <Admin>
             <admNetwork></admNetwork>
             <admUsers></admUsers>
          </Admin>
          <Logging></Logging>
       </Module1>
       ...  Now I can have 1 or many Modules depending on what the xml file  has in it.
       <Module*n>
    </device>Other problems. Some of the information I want to store as a sortable Table, but I cannot seem to get any of the sort methods to work. They work if I just open a browser, and run the html file, but if I stick the html file into the JEditorPane it does not work? - any suggestions?
    Also, can I pass a JTabbebPane to the JEditorPane, or can I create a tabbed pane in html that will do the same thing.
    I am working with a very small device. It does not have a web application container like Tomcat on it. Just Apache, and Java. That is why I am using Swing.

    Using 'productAttribute/text()' gets you all three productAttribute nodes and then grabs all the text under that node. It simply concatenates together all the text under the desired node, hence the results you are seeing. If you want to get the text for each child node separately, then you need to do something like (assumes 10.2.x.x or greater)
    WITH your_table AS (SELECT
    '<root><productAttribute>
    <name>Baiying_attr_03</name>
    <required>false</required>
    </productAttribute>
    <productAttribute>
    <name>Baiying_attr_04</name>
    <required>false</required>
    </productAttribute>
    <productAttribute>
    <name>Baiying_attr_05</name>
    <required>false</required>
    </productAttribute></root>' xmldata
    FROM DUAL)
    -- Above simulates your DB table as I don't have it
    -- You only care about the following
    SELECT xt.*
      FROM your_table yt,
           XMLTable('/root/productAttribute'
                    PASSING XMLTYPE(yt.xmldata)
                    COLUMNS
                    prd_nm   VARCHAR2(30)  PATH 'name',
                    prod_rqd VARCHAR2(5)   PATH 'required') xt;Note: I added a <root> node as you had just provided a XML fragment. You will need to adjust accordingly.
    The above produces
    PRD_NM                         PROD_RQD
    Baiying_attr_03                false
    Baiying_attr_04                false
    Baiying_attr_05                false

  • Problem with JPopupMenu and JTree

    Hi,
    Is there any way to have different JPopupMenu for every node.
    When I right click on the treenode there is popup menu have a "*JCheckBoxMenuItem*". By default the value of that checkbox is false. Now when i try to right click on a particular node and select the checkbox the selected value gets applied to rest of all nodes also.
    How can i just set the value of the checkbox to one perticular node.
    my code is
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreePopupMenuTest {
      public JComponent makeUI() {
        JTree tree = new JTree();
        tree.setComponentPopupMenu(new TreePopupMenu());
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(tree));
        p.setPreferredSize(new Dimension(320, 240));
        return p;
      class TreePopupMenu extends JPopupMenu {
        private TreePath path;
        private JCheckBoxMenuItem compress=new JCheckBoxMenuItem("Compress");
        public TreePopupMenu() {
          super();
          add(compress);
          compress.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ie) {
                            if(compress.getState()){
                                 compress.setState(true);
                                    System.out.println("compress clicked");
                            else{
                                 compress.setState(false);
                                    System.out.println("uncompress");
        public void show(Component c, int x, int y) {
          JTree tree = (JTree)c;
          path = tree.getPathForLocation(x, y);
          if(path!=null && path==tree.getAnchorSelectionPath()) {
            super.show(c, x, y);
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TreePopupMenuTest().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }Please help me as soon as possible.
    Thanks.
    Edited by: Kavita_S on Apr 23, 2009 11:49 PM

    Hi,
    Do you know this link?
    [How to Use Trees|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html]
    Please help me as soon as possible.Sorry that I'm not good at English, I don't understand what you mean.
    Anyway, here's a quick example:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreePopupMenuTest3 {
      public JComponent makeUI() {
        JTree tree = new JTree();
        tree.setComponentPopupMenu(new TreePopupMenu());
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(tree));
        p.setPreferredSize(new Dimension(320, 240));
        return p;
      class TreePopupMenu extends JPopupMenu {
        private TreePath path;
        private JCheckBoxMenuItem compress = new JCheckBoxMenuItem("Compress");
        public TreePopupMenu() {
          super();
          add(compress);
          compress.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ie) {
              if (compress.getState()) {
                System.out.println("compress clicked");
                setSelectedPath(path, true);
              } else {
                System.out.println("uncompress");
                setSelectedPath(path, false);
        public void show(Component c, int x, int y) {
          JTree tree = (JTree)c;
          path = tree.getPathForLocation(x, y);
          if (path!=null && path==tree.getAnchorSelectionPath()) {
            compress.setState(isSelectedPath(path));
            super.show(c, x, y);
      class MyData {
        public boolean flag;
        public String name;
        public MyData(String name, boolean flag) {
          this.name = name;
          this.flag = flag;
        @Override public String toString() {
          return name;
      //private Set<TreePath> selectedPath = new HashSet<TreePath>();
      private void setSelectedPath(TreePath p, boolean flag) {
        //if (flag) selectedPath.add(p);
        //else    selectedPath.remove(p);
        DefaultMutableTreeNode node =
              (DefaultMutableTreeNode)p.getLastPathComponent();
        Object o = node.getUserObject();
        if (o instanceof MyData) {
          ((MyData)o).flag = flag;
        } else {
          node.setUserObject(new MyData(o.toString(), flag));
      private boolean isSelectedPath(TreePath p) {
        //return selectedPath.contains(p);
        Object o =
              ((DefaultMutableTreeNode)p.getLastPathComponent()).getUserObject();
        return (o instanceof MyData)?((MyData)o).flag:false;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TreePopupMenuTest3().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

  • JSplitPane, JScrollPane and JTree resizing

    Hi,
    In a JSplitPane, I have, in the left part, a JScrollPane, containing a JTree and, in the right part, I have an other panel.
    When I click on different nodes in the JTree, the width of the left part changes, so the JSplitPane separator moves. How to avoid that ? I would prefer a scrolling move inside the JScrollPane !
    I am using JDK 1.3
    Thanks
    Olivier Scalbert

    Try to define the JScrollPane as
    public JScrollPane(Component view, int vsbPolicy, int hsbPolicy)
    Use vsbPolicy and hsbPolicy like the VERTICAL_SCROLLBAR_AS_NEEDED
    HORIZONTAL_SCROLLBAR_AS_NEEDED respectively.
    Then define the setPreferredSize to your JScrollPane. This preferredSize must be smaller than the size of the Component view if you want to see the ScrollBar.
    By the way, when you define your JSplitPane have to define the setOneTouchExpandable(true);?

  • Vector and Jtree 4Duke

    hi
    i am having poblem with my jtree as i am not able to show the object in my vector as a different node
    {each object is node of my tree}
    unfortunately they all appear flat in the root, and in sequence{as one node} ??
    i have done everything but still no answer??
    thanks in advance for any solution
    public class Gui extends JFrame
    {  Vector root = new Vector();
    public JTree theTree ;
    public SERGui( )
    System.out.println(root.size());//root vector is empty
    roott = new DefaultMutableTreeNode (root);
    model = new DefaultTreeModel (roott) ;
    theTree = new JTree (model);      
    public Vector addOne(String newString)
    if (!root.contains(getQuery))
               root.add(newString);
    model.reload();
    // //updateTree(); i also try this method whiich does not work
    return root;
    public void updateTree(){
    DefaultMutableTreeNode v = (DefaultMutableTreeNode)theTree.getModel().getRoot();
    for(int i=0;i<root.size();i++)
                   DefaultMutableTreeNode node = (DefaultMutableTreeNode)root.elementAt(i);
                   roott.add(node);
    ((DefaultTreeModel)theTree.getModel()).reload(v);
    //DefaultMutableTreeNode node = null;
    print_vector(root);
      //root.clear();
         }and my other class
    where i call this methos is as follow
    Class Search()
    public void countWord(String newString)
    {Gui.addOne(newString);
    }}

    You are passing a Vector into the constructor of the DefaultMutableTreeNode to create the root of your tree. The DefaultMutableTreeNode will use this object's string representation (by calling toString on whatever object you pass in its constructor) as the name of the tree node. So basically you will see the entire contents of the vector as the name of your root node.
    You need to traverse your vector, and use each element to create a DefaultMutableTreeNode and add it to your root node.
    here is the modified code
    public class Gui extends JFrame {
    private Vector rootVector = new Vector();
    private JTree theTree;
    private DefaultMutableTreeNode rootNode;
    private DefaultTreeModel model;
    public Gui() {
    System.out.println(rootVector.size());
    //root vector is empty
    rootNode = new DefaultMutableTreeNode("Root");
    model = new DefaultTreeModel(rootNode);
    theTree = new JTree(model);
    public Vector addOne(String newString) {
    if (!rootVector.contains(newString)) {
    rootVector.add(newString);
    updateTree();
    return rootVector;
    public void updateTree() {
    rootNode.removeAllChildren();
    for (int i = 0; i < rootVector.size(); i++) {
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(
    rootVector.elementAt(i));
    rootNode.add(node);
    ((DefaultTreeModel) theTree.getModel()).reload(rootNode);
    Hemant Mahidhara

  • JSplitPane and Jtree

    Hi all,
    in my window I've got a JSplitPane with the left component that is a JScrollPane with a Jtree (used as a menu), while in the right side a customized JPanel that changes depending on the selection in the tree on the left.
    My panels are initially created as follows:
         this.splitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
         this.splitter.setOneTouchExpandable(true);
    JScrollPane leftPanel = new JScrollPane( this.menuTree );
              leftPanel.setMinimumSize( new Dimension(300,300) );     
              leftPanel.setMaximumSize(leftPanel.getMinimumSize());
              // add the leftt and right panels
              this.splitter.setLeftComponent( leftPanel );
              this.imagePanel = new ImagePanel(ComponentBuilder.getLogoPath());
              this.rightPanel = this.imagePanel;
              this.splitter.setRightComponent(this.rightPanel);
              // add the splitter to myself
              this.add(new JScrollPane(this.splitter));where the imagepanel is a working panel that shows the project logo. Now what happens is that:
    1) the logo is cutted to a size I don't know how is calculated, since the image panel is working fine (if I place on a separate window I can see the image right)
    2) most important when a user selects something in the tree on the left panel, so the right panel changes, the left panel is moved around the window depending on the size of the right panel.
    Is it possible to fix the left panel not only as size, but also in the position of the window, thus the remaining part of the window will be occupied by the right panel without moving the left one? In my frame I'm using a BorderLayout, and the panel containing the splitpane is set at the center (no components on the right and on the left).
    Thanks,
    Luca

    Thanks for your reply, but the only thing I noticed is that the code you're showing works a little more with sizes, that is something I've already tried. By the way, the following is a running example that loads a tree/menu and the logo.png image.
    Any idea about its behaviour?
    Thanks,
    Luca
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.awt.image.*;
    class ImagePanel extends JPanel implements ImageObserver
         * The image to display
        protected Image image=null;
         * This flag indicates if the image is complete or not.
        protected boolean isComplete=false;
         * The dimension of the panel.
        protected int width=0,height=0;
         * This is the message to display during loading.
        protected String message="Loading...";
         * Default constructor.
         * @param image the image object.
        public ImagePanel(Image image)
              super();
              this.image=image;
         * Overloaded constructor. It try to load the image itself. You should use
         * this to avoid image flicking problems. This method use all the
         * capabilities of the ImageObserver.
         * @param image the image file name
        public ImagePanel(String image) {
              super();
              /* now load the image */
              Toolkit tk=Toolkit.getDefaultToolkit();
              this.image=tk.getImage(image);
              /* use the media tracker to wait untill the image is not loaded */
              try{
                  MediaTracker tracker=new MediaTracker(this);
                  tracker.addImage(this.image,0);
                  tracker.waitForID(0);
                  this.isComplete=true;
                  /* now that the image is fully loaded I need to resize the panel to
                  the size of the image */
                  this.width=this.image.getWidth(this);
                  this.height=this.image.getHeight(this);
                  this.setSize(width,height);
                  this.setMinimumSize(getSize());
                  this.setMaximumSize(getSize());
                  this.setVisible(true);
              catch(InterruptedException e){
                  this.message="Exception during loading process!";
                  this.isComplete=false;
         * Draw the image.
        public void paint(Graphics device)   {
              super.paint(device);
              if(this.isComplete==true)     {
                  device.drawImage(this.image,0,0,this.width,this.height,this);
              else     {
                  device.setColor(Color.RED);
                  device.drawString(this.message,20,20);
         * The update image method. This method is called for every update and or
         * error.
        public boolean imageUpdate(Image image,int infoFlags, int x, int y,
                        int width, int height)
              if((infoFlags & ALLBITS)==0)
                  /* the image is complete */
                  this.isComplete=true;
                  repaint();
                  this.setVisible(true);
                  return false;
              else
              if((infoFlags & ERROR)==0 || (infoFlags & ABORT)==0 )
                  /* error or abort */
                  this.isComplete=false;
                  this.message="Error during load process (or abort)";
                  this.repaint();
                  return true;
              else
              if((infoFlags & SOMEBITS)==0)
                  /* some other data loaded, show the loading process percent */
                  int originalWidth=this.image.getWidth(this);
                  int originalHeight=this.image.getHeight(this);
                  int currentWidth=image.getWidth(this);
                  int currentHeight=image.getHeight(this);
                  /* now calculate the total of pixels */
                  long originalTotal=originalWidth*originalHeight;
                  long currentTotal=currentWidth*currentHeight;
                  /* now calculate the percent */
                  float percent=(float)currentTotal/(float)originalTotal *100;
                  /* set the string */
                  this.message="Loading progress: "+(int)percent+" % done";
                  this.repaint();
                  return true;
              return true;
    public class MainPanel extends JPanel {
          * The split pane used for this panel.
         protected JSplitPane splitter = null;
          * The menu tree of this panel.
         protected JTree menuTree = null;
          * The parentFrame frame of this panel
         protected JFrame parentFrame = null;
          * The panel on the right of the window.
         protected JComponent rightPanel = null;
          * The menuTreeRoot node of the menu.
         protected DefaultMutableTreeNode menuTreeRoot = null;
          * The action menu of the JFrame that contains this panel. Such menu is changed depending on the panel
          * shown on the right panel.
         protected JMenu actionMenu = null;
          * The image panel with the image of the logo.
         protected ImagePanel imagePanel = null;
         public final String ROOT_STRING = "Gestione delle risorse umane";
         public final String LEVEL1A_STRING = "Parametrizzazione";
         public final String LEVEL2AA_STRING = "Competenze & Famiglie di competenze";
         public final String LEVEL2AB_STRING = "Gestione dei ruoli";
         public final String LEVEL2AC_STRING = "Associazione ruolo-competenza";
         public final String LEVEL1B_STRING   = "Varie";
         public final String LEVEL2BB_STRING = "Province";
         public final String LEVEL2BC_STRING = "Citta'";
         public final String LEVEL2BD_STRING = "Livelli di istruzione";
         public final String LEVEL2BE_STRING = "Livelli di competenza";
         public final String LEVEL3A_STRING   = "Personale";
         public final String LEVEL3AA_STRING = "Anagrafica di base";
         public final String LEVEL3AB_STRING  = "Ruoli, Competenze e Gradi di Istruzione";
         public final String LEVEL3AC_STRING  = "Storia delle valutazioni delle competenze";
         public final String LEVEL3AD_STRING  = "Valutazione";
          * Default constructor.
          * @param parentFrame the jframe that contains this panel
         public MainPanel(JFrame parent, JMenu actionMenu){
              super();
              this.parentFrame = parent;
              this.initGUI();
              this.actionMenu = actionMenu;
          * Shows the components on the main panel.
         public synchronized void initGUI(){
              // create the split pane
              this.splitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
              this.splitter.setOneTouchExpandable(true);
              //this.splitter.setResizeWeight(0);                    // the right panel gets all the extra space
              // create the left panel with the tree
              DefaultMutableTreeNode root = new DefaultMutableTreeNode(ROOT_STRING);
                   DefaultMutableTreeNode level1a = new DefaultMutableTreeNode(LEVEL1A_STRING);
                        ContainerTreeNode level2aa = new ContainerTreeNode(LEVEL2AA_STRING);     // skills and families
                   DefaultMutableTreeNode level2ab = new DefaultMutableTreeNode(LEVEL2AB_STRING);
                        DefaultMutableTreeNode level2ac = new DefaultMutableTreeNode(LEVEL2AC_STRING);
                   DefaultMutableTreeNode level1b = new DefaultMutableTreeNode(LEVEL1B_STRING);
                        DefaultMutableTreeNode level2bb = new DefaultMutableTreeNode(LEVEL2BB_STRING);
                        DefaultMutableTreeNode level2bc = new DefaultMutableTreeNode(LEVEL2BC_STRING);
                        DefaultMutableTreeNode level2bd = new DefaultMutableTreeNode(LEVEL2BD_STRING);
                        DefaultMutableTreeNode level2be = new DefaultMutableTreeNode(LEVEL2BE_STRING);
                   DefaultMutableTreeNode level3a = new DefaultMutableTreeNode(LEVEL3A_STRING);
                        DefaultMutableTreeNode level3aa = new DefaultMutableTreeNode(LEVEL3AA_STRING);
                        DefaultMutableTreeNode level3ab = new DefaultMutableTreeNode(LEVEL3AB_STRING);
                        DefaultMutableTreeNode level3ac = new DefaultMutableTreeNode(LEVEL3AC_STRING);
                        DefaultMutableTreeNode level3ad = new DefaultMutableTreeNode(LEVEL3AD_STRING);
              // create the tree
              this.menuTreeRoot = root;
              level2ab.add(level2ac);
              level1a.add(level2aa);
              level1b.add(level2bc);
              level1b.add(level2bb);
              level1b.add(level2bd);
              level1b.add(level2be);
              level3a.add(level3aa);
              level3a.add(level3ab);
              level3a.add(level3ac);
              level3a.add(level3ad);
              root.add(level3a);
              root.add(level2ab);
              root.add(level1a);
              root.add(level1b);
              this.menuTree = new JTree(root);
              this.menuTree.setSize(200,200);
              JScrollPane leftPanel = new JScrollPane( this.menuTree );
              leftPanel.setMinimumSize( new Dimension(300,300) );     // it does not affects the dimension, but avoid to resize the left panel
              leftPanel.setMaximumSize(leftPanel.getMinimumSize());
              // add the leftt and right panels
              this.splitter.setLeftComponent( leftPanel );
              this.imagePanel = new ImagePanel("logo.png");
              this.rightPanel = this.imagePanel;
              this.rightPanel.setSize(400,400);
              this.splitter.setRightComponent(this.rightPanel);
              // add the splitter to myself
              this.add(new JScrollPane(this.splitter));
         public static void main(String argv[]){
             JFrame f = new JFrame();
             f.setSize(400,400);
             f.add(new MainPanel(f,null));
             f.setVisible(true);
    }

  • Leaf and JTree

    Hi all,
    I would like to ask a small question about JTree. Is there a way to not display leaf without removing them from the tree?
    Actually I used a tricky whay by crating my own DefaultTreeCellRenderer and checking when it's the leaf I set the preferedSize to 0. However, by using this tricky way i have some weird behaviour with scrollPane.
    Does anyone has an idea to not display leaf in a JTree?
    Regards,
    Raffael

    Raffael wrote:
    Hello,
    thanks for your anserw. However, creating your own JTreeModel allow you to specify if a node is a leaf or not. But you will not being able to not draw it via the tree model or I m wrong?Your custom TreeModel will have to 'hide' the leaf nodes from objects that ask about them. Here's an example that wraps a DefaultTreeModel:
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.WindowConstants;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    public class HiddenLeaves {
        HiddenLeaves() {
            JFrame f= new JFrame();
            f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
            DefaultMutableTreeNode nodeA = new DefaultMutableTreeNode("Node A");
            nodeA.add(new DefaultMutableTreeNode("Leaf One"));
            nodeA.add(new DefaultMutableTreeNode("Leaf Two"));
            nodeA.add(new DefaultMutableTreeNode("Leaf Three"));
            DefaultMutableTreeNode nodeB = new DefaultMutableTreeNode("Node B");
            nodeB.add(new DefaultMutableTreeNode("Leaf Four"));
            nodeB.add(new DefaultMutableTreeNode("Leaf Five"));
            nodeB.add(new DefaultMutableTreeNode("Leaf Six"));
            root.add(nodeA);
            root.add(nodeB);
            final FilteredTreeModel model = new FilteredTreeModel(new DefaultTreeModel(root));
            final JTree tree = new JTree(model);
            f.add(new JScrollPane(tree), BorderLayout.CENTER);
            JButton b = new JButton("Toggle Leaf Display");
            b.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    boolean visible = model.isShowingLeaves();
                    model.setShowingLeaves(!visible);
                    tree.repaint();
            f.add(b, BorderLayout.SOUTH);
            f.setSize(400,300);
            f.setVisible(true);
        public static void main(String[] args) {
            new HiddenLeaves();
        private static class FilteredTreeModel implements TreeModel {
            private boolean showingLeaves = true;
            private DefaultTreeModel delegate;
            public FilteredTreeModel(DefaultTreeModel delegate) {
                this.delegate = delegate;
            public void setShowingLeaves(boolean show) {
                this.showingLeaves = show;
                delegate.reload();
            public boolean isShowingLeaves() {
                return showingLeaves;
            public Object getChild(Object parent, int index) {
                Object child = delegate.getChild(parent, index);
                if (!isShowingLeaves() && delegate.isLeaf(child)) {
                    child = null;
                return child;
            public int getChildCount(Object parent) {
                int count = delegate.getChildCount(parent);
                if (!showingLeaves) {
                    int newCount = count;
                    for (int i = 0; i < count; i++) {
                        if (delegate.isLeaf(delegate.getChild(parent, i))) {
                            newCount--;
                    count = newCount;
                return count;
            public int getIndexOfChild(Object parent, Object child) {
                int index = delegate.getIndexOfChild(parent, child);
                if (!showingLeaves) {
                    if (delegate.isLeaf(child)) {
                        index = -1;
                return index;
            public Object getRoot() {
                return delegate.getRoot();
            public boolean isLeaf(Object node) {
                return delegate.isLeaf(node);
            public void valueForPathChanged(TreePath path, Object newValue) {
                delegate.valueForPathChanged(path, newValue);
            public void addTreeModelListener(TreeModelListener l) {
                delegate.addTreeModelListener(l);
            public void removeTreeModelListener(TreeModelListener l) {
                delegate.removeTreeModelListener(l);
    }

  • JList and JTree

    Hello,
    I have a list of servers in a JList( is a seperate class) and when i am selecting a server name from the JList i am calling this value in my main class and I am trying to use this selected value from the Jlist to create a new JTree node but the value is not being displayed as a node.
    Any body having ideas as to why?
    Reg,
    suri

    Hello,
    Thanks for ur replies. I have tried the following way but still no results the node is not appearing in the JTree.
    Here logon(this is a listBox class and contains a JList with a list of server names)
    and root1 is the parent .
    DefaultMutableTreeNode new1 = new DefaultMutableTreeNode(logon.getValue(), true);
         int childCnt = root1.getChildCount();
         treeModel.insertNodeInto(new1, root1, childCnt);
    treeModel.reload(new1);
    treeModel.nodeStructureChanged(new1);
    JTree1.revalidate();
    JPanel1.revalidate();
    Any body any ideas .
    Thanks,
    reg,
    suri

  • ZipFiles and JTree

    I am developing a tool which compares to source zip files and generate report. I got stuck in the middle of the project.
    Do anybody help in extracting z zip file and displaying the whole contents in zip file using JTree format. I was able to extract the contents from the zip file but couldn't display those contents using JTree.

    Follow the bouncing link. As always Google is your friend.
    http://www.google.com/search?hl=en&q=Java+%2B+extracting+zip+file
    Cheers,
    PS

  • Database and JTree

    I have table in access entitled employees and wish to generate a JTree to show the organizational heirarchy of the company. I feel like I've followed the steps properly but the Jtrees either don't work or they work with the wrong data.
    "Perform a query to obtain the name of the employee. If you are at the root node (level 0), just change the value of the current node to the name you got from the query, otherwise, create a child node and set its value to be that name. Perform another query to get the employee IDs of all the employees whose manager is the current employee. Loop through this result set, recursively calling the method for each of the employees in the resultset from step (4)."[]
        public static void generateTree(DefaultMutableTreeNode node, int id, int level){
            DbSource dbs = new DbSource("EmpDb");
            if (dbs.isConnected()){
             boolean success = dbs.processQuery("select firstname, lastname from employees", false);
             if(success){
                 while(dbs.nextRecord()){
                  DefaultMutableTreeNode newNode;
                    if (level==0){
                        node.setUserObject(dbs.getField(1)+ " " + dbs.getField(2));
                        newNode=node;
                    else{
                        newNode = new DefaultMutableTreeNode(dbs.getField(1) + " " + dbs.getField(2));
                        node.add(newNode);               
                 boolean success2 = dbs.processQuery("select employeeid from employees where " + id+ " = manager", false);
                 if (success2){
                 while (dbs.nextRecord()){
                      generateTree(newNode, id, level+1);                      
        }Any quick hints are appreciated.

    Well, you didn't say what was wrong with the result of this. But that doesn't matter because I can see a lot of things wrong with the code.
    First you don't have anything that gets the level-zero node. (The president of the company or whatever that is.) You should do this outside the recursively-called method and create a node that contains that person's name. Then call the method, passing it that node.
    Second, in your posted code you have something that reads the entire file at every level. What's that for?
    Third, the last four lines of that method look like the actual code you need: get the employees who report to the manager in the current node. However you need something that creates a new node for each of those employees and adds it to the manager node.
    Fourth, you don't seem to use that "level" parameter anywhere. I don't think you have any need for it.
    Fifth, and I don't know if this is a problem, you will need to be able to process several DbSource objects simultaneously. Possibly you can, but it's possible to code that sort of thing so that you can't.

Maybe you are looking for

  • How to find out the host, client and sid for jdbc connection

    I've just registered at oracle application express and would like to test my java programm from my pc I need the connection string in form: "jdbc:oracle:thin:@host:port:sid"; where can I found out my host, port and sid? Thanks! Edited by: 1009284 on

  • Apple 4S and itunes 10.5 Audio Issue

    I bought my 4S yesterday. It would not SYNC to my older version of itunes on my Windows XP PC. I was forced to run the upgrade to 10.5. I can sync, but my 4S won't let me play the music that transferred to it. Also, 98% of my music in itunes now soun

  • HELP ME Please ! No Blue Lights on both of my WRTU54G-TM Routers behind a WRT54GX2 Router

    I've had this configuration installed and working for the past two months as such: Motorola Cable Modem - COX Cable ISP - 15Mbps down / 5Mbps up ; actual rated is higher on speedtest.net Linksys Router - WRT54GX2 (I'll refer to this as main Router) L

  • Problem with Pages text breaks

    Hi guys. As a writer, I'm going to be using Pages on my brand new MacBook Pro 13" (I just switched from Windows) quite a lot, so it really ticks me off that whenever I insert text in a line in a paragraph, the line below it gets separated from the re

  • Power failure then iPhoto library= POOF! :-(    PLEASE HELP!

    Power failure then iPhoto> library= POOF! We had a power failure and of course iPhoto was open when my computer was improperly shut down. After powering up, I did the following; repaired permissions and ran disk utility (no problems found). Upon open