Selection in a JEditorPane

Hello,
MY code is as follows:
HTMLDocument document = ( HTMLDocument )jeditorpane1.getDocument();
String htmlString = "<ol><li><p></p></li></ol>";
HTMLEditorKit newKit = jeditorpane1.getKit();
try
newKit.insertHTML( document, editorPane.getCaretPosition(), htmlString, 1, 0, HTML.Tag.OL );
jeditorpane1.setCaretPosition( editorPane.getCaretPosition() - 1 );
jeditorpane1.setCursor( Cursor.getDefaultCursor() );
jeditorpane1.requestFocus();
jeditorpane1.getCaret().setSelectionVisible( true );
this.dispose();
catch( BadLocationException bl )
bl.printStackTrace();
catch( IOException ioe )
ioe.printStackTrace();
I am inserting a ordered list in my jeditorpane and now i want to select that inserted ordered list in the jeditorpane using the mouse double click or mouse drag. Anybody any ideas as how i can select the inserted ordered list using the mouse .

Thank you very much for your reply, this did the trick:
EditorKit editorKit = m_pane.getEditorKit();
StringWriter sw = new StringWriter();
try
     editorKit.write(sw, m_pane.getDocument(), m_pane.getSelectionStart(), m_pane.getSelectionEnd() -      m_pane.getSelectionStart());
catch (IOException ex)
     logger.error("Error writing selection", ex);
catch (BadLocationException ex)
     logger.error("Error writing selection", ex);
sw.flush();
logger.info("String writer tostring: " + sw.toString());

Similar Messages

  • JEditorPane insert text at caret?

    Does anyone know how to insert text at the current position of the caret in a JEditorPane?
    Additionally, is there a way to insert text before and after a specific selection within a JEditorPane?
    Am I using the right object for these types of purposes, or is there another Swing component that would be better suited?

    I found my answer in: [http://forums.sun.com/thread.jspa?forumID=57&threadID=5264416]
                   public boolean insertHTML(InEditorPane textAreaPane, String text, int offset) {
              HTMLDocument doc = (HTMLDocument) textAreaPane.getDocument();
              HTMLEditorKit kit = (HTMLEditorKit) textAreaPane.getEditorKit();
              boolean res = true;
              try {
                   // kit.insertHTML(doc, offset, text, 0, 0, null);
                   System.out.println("reading from string reader");
                   kit.read(new StringReader(text), doc, offset);
                   System.out.println(textAreaPane.getText());
              } catch (Exception e) {
                   System.out.println("error inserting html: " + e);
                   res = false;
              return res;
         }           But now I have kind of the oposite problem: when I type text in the panel, new lines are saved as '\n' instead of "<br>", so when I save the text and show it again I get one long line...

  • How to get html tags from JEditorPane ??

    Hi All,
    I have a html page that i am displaying in a JEditorPane with all support to styles and images as i have set content type of pane to text/html.
    When a user selects some text in JEditorPane, i want to get the content of the selected text, but not from text, but from HTML tags. In short what i want to know how can i get the html tags of the selected text in JEditorPane.
    Please tell me how to solve this problem.
    Thanks in advance
    Kind regards
    Chetan Chandarana

    thats very correct, but things is that the tags which i displayed are not getting retrived back from the textpane, specially some new line characters are coming.....any reason ?
    thanks for the reply
    kind regards
    Chetan Chandarana

  • JeditorPane text selection problem due to line feeds and carriage returns

    Hi folks,
    I have a jEditorPane (text/plain) that contains a document in which the user has highlighted some text. I want to pull the selected text from the pane, do some processing on it, and then put the altered text back in the same position.
    First I get the starting and ending position of the highlighted text
    int mySelStart = myJEditorPane.getSelectionStart();
    int mySelEnd = myJEditorPane.getSelectionEnd();Then I get all the text from the pane and (in theory) strip out the portion the user highlighted
    String myPaneText = myJEditorPane.getText();
    String mySelectedText = myPaneText.substring(mySelStart,mySelEnd);But the text string in mySelectedText never matches what the user originally highlighted. The starting and ending positions are off by the number of carriage returns that proceed the highlighted text in the document. It appears that while in the jEditorPane Java treats the carriage return as one characters, but once the info is in the myPaneText field Java treats the carriage return as two characters.
    Has anyone encountered this before? Am I doing something wrong? To fix the problem I'm looping through the entire document to find out how many carriage returns proceed the highlighted text, but there has to be an easier way.
    Thanks

    It appears that while in the jEditorPane Java treats the carriage return as one
    characters, but once the info is in the myPaneText field Java treats the carriage
    return as two characters.Correct on a Windows platform. Check out my posting here for a one line solution:
    http://forum.java.sun.com/thread.jspa?forumID=31&messageID=1464594

  • Rendered Text Selection in JEditorPane's

    Hello,
    I am having trouble figuring out how the select(int, int) and its various other equivalents (i.e. sequential calls to setCaretPosition(int) and moveCaretPosition(int)) are used in JEditorPane's. Supposedly, if you call select(int, int),it does a setCaretPosition(int) and moveCaretPosition(int), but what is going on if my calls seem to fail without any exceptions (i.e. they seem to be executed but with no visible results rendered onto the component). In fact, the String that should be selected and returned by getSelectedText() is returned as null. However, when my calls are placed inside any listener in a nonconditonal context such that they are always called, then the selection happens. Is there something equivalent to update() or repaint() for JEditorPane's that I should be calling that is either undocumented or just obscure???
    -J

    I'm not sure whether this will help, seeing as you just upgraded, but worth a try:
    If Dreamweaver is behaving in an odd way, it frequently means you have a corrupt personal configuration folder.
    Close Dreamweaver, locate the personal configuration folder, and rename it.
    When you restart Dreamweaver, it should create a new configuration folder with all the program defaults.   
    For details of how to find the configuration folder, see this page in the Dreamweaver FAQ.
    Nadia
    Adobe® Community Expert : Dreamweaver
    http://www.perrelink.com.au
    Unique CSS Templates | Tutorials | SEO Articles
    http://www.DreamweaverResources.com
    http://twitter.com/nadiap

  • Using JEditorPane.selected() with embedded tags.

    Ok, I've been searching the forums and tutorials for about an hour tonight, and I've seen this question asked in many forms but never answered.
    I am writing an applet which uses embedded HTML and some custom tags in a sub-class of JEditorPane that I wrote. I need to be able to get the position of certain tags within the text, which I can do using the JEditorPane.getText() method. But now that I've found the right tags, how can I highlight text contained within them in the visible Pane?
    e.g.:
    getText() returns
    <html>
    <head>
    </head>
    <body>
    Check</shu_ind> this <shu_dep>out</shu_dep>
    </body>
    </html>
    And these shu tags are the ones I want to use. I can parse the text and grab the right position, but when I select(begin,end), it's off by a lot b/c select() doesn't look at any embedded info.
    What can I do?

    I don't think it's the same as I'm doing. Essentially, I have a JEditorPane subclass, which just has a few custom tags in it. I don't need them to be recognized by java, since it will be uneditable, but I just need to know how to convert from the getText() locations to the actual displayed text locations.
    Also, when I set the text as text/html, it creates a bunch of extra HTML tags, so it's larger than the original String used to create it.

  • Setting selection in JEditorPane

    Hi guys!
    I have somtehing like this:
    JEditorPane pane = new JEditorPane();
    pane.setSelectionColor(Color.Blue);
    pane.selectAll();
    but nothing happens. I mean, the text is scrolled as if the selection was made, but color doesn't changes. If you select some text manually, it works fine.
    Any ideas?

    OK guys!
    I've found it.
    It was a question of focus.
    thank anyway

  • JEditorPane - getting Selected Text or Active Line number

    Is there any predefined method that will give me the current line selected or the line at which the cursor is?
    I am displayed a piece of java code in my JEditorPane, the user can browse through the entire file.. and I need to call an event when a user selects/double clicks a particular module name or based on the current line number where the cursor is. Is there any simple technique to get the line number or the current highlighted text?
    I am relatively new to JEditorPane. Also If you think I shoudl go upon writing an actionListener, a mouse of keyboard... please let me know how to go about it. I keep getting confused.
    Thanks,
    Sirish

    In the future, Swing related questions should be posted in the Swing forum.
    there any simple technique to get the line number Well, a JEditorPane is typically used for displaying HTML. So does a line number make sense when you don't know the contents of the HTML. If you simply have lines of text then you should be using a JTextArea or a JTextPane.
    Check out this posting for a method to return the line number at a give caret postion:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=608220
    or the current highlighted text?Read the API. A get??? method will do what you want.

  • Help - JEditorPane drag selected text behavior/problem

    Hi All,
    I'm working at adding new functionality to the JEditorPane. Everything was going ok, but I noticed this interesting behavior that hopefully there is a solution to.
    When you select some text in the JEditorPane with the mouse and then drag the selected text to another location, the text moves just fine. However, depeding on when you drag the text, something interesting happens.
    Here is the senerio. While the text is already selected you noticed the cursor blinking.
    (1) If you drag the selected text while the blinking cursor IS visible, the cursor will continue to blink after you drag the text to its destination.
    (2) If you drag the selected text while the blinking cursor IS NOT visible, the cursor will be invisible after you drag the text to its destination.
    So (2) is really the problem. The only way I've been able to get the cursor to start blinking again is to issue a cut, copy or paste method from the JEditorPane object.
    Has anyone else found this problem and maybe a solution to it. I've disabled all the extra stuff I extended on the JEditorPane class, but it didn't seem to make a difference.
    Thanks.
    Justin Circelli

    There are several approaches. You can add FocusListener to the drop target or drag source and put your code in focusGained() or focusLost() accordingly.
    Another way is to return focus to the drag source if DnD failed as you tried. First check whether mouseReleased(0 is invoked. If it's invoked try to put your code into SwingUtilities.invokeLater()
    regards
    Stas

  • Trying to "Select All" using the JEditorPane

    Hello,
    I am constructing a web browser and trying to implement the standard copy, paste and select all actions.
    I am having a little trouble, I have searched for the answer but I'm not having much luck and could do with some help please.
    Basically I am trying to select all the text displayed by a URL
    I have tried getStartPosition/getEndPosition but that method would not work with the editor pane
    I have tried editorPane.selectAll() but that gives me the actual java code for the pane somehow...
    I would really appreciate someones help, I hope it's simple
    cheers

    class SelectAll extends TextAction
         public SelectAll()
              super("Select All");
         public void actionPerformed(ActionEvent e)
              JTextComponent component = getFocusedComponent();
              component.selectAll();
    }

  • How can an applet retrieve the values of a HTML form shown in a JEditorPane

    Hi,
    I'm doing an applet that contains a JTree and a JEditorPane
    among other components. Each node of the JTree represents some
    information that is stored in a database, and whenever a JTree
    node is selected, this information is recovered and shown in
    the JEditorPane with a html form. To make the html form,
    the applet calls a servlet, which retrieves the information of
    the node selected from the database. This information is stored
    like a XML string, and using XSLT, the servlet sends the html
    form to the applet, which shows it in the JEditorPane.
    My problem is that I don't know how I can recover new values
    that a user of the application can introduce in the input fields
    of the html form. I need to recover this new values and send them
    to another servlet which store the information in the database.
    If someone could help me I'd be very pleased.
    Eduardo

    At least I found a fantastic example. Here it is:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    public class FormSubmission extends JApplet {
    private final static String FORM_TEXT = "<html><head></head><body><h1>Formulario</h1>"
    + "<form action=\"\" method=\"get\"><table><tr><td>Nombre:</td>"
    + "<td><input name=\"Nombre\" type=\"text\" value=\"James T.\"></td>"
    + "</tr><tr><td>Apellido:</td>"
    + "<td><input name=\"Apellido\" type=\"text\" value=\"Kirk\"></td>"
    + "</tr><tr><td>Cargo:</td>"
    + "<td><select name=\"Cargo\"><option>Captain<option>Comandante<option>General</select></td>"
    + "</tr><td colspan=\"2\" align=\"center\"><input type=\"submit\" value=\"Enviar\"></td>"
    + "</tr></table></form></body></html>";
    protected HashMap radioGroups = new HashMap();
    private Vector v = new Vector();
    public FormSubmission() {
    getContentPane().setLayout(new BorderLayout());
    JEditorPane editorPane = new JEditorPane();
    editorPane.setEditable(false);
    editorPane.setEditorKit(new HTMLEditorKit()
    public ViewFactory getViewFactory() {
    return new HTMLEditorKit.HTMLFactory() {
    public View create(Element elem) {
    Object o = elem.getAttributes().getAttribute(javax.swing.text.StyleConstants.NameAttribute);
    if (o instanceof HTML.Tag)
    HTML.Tag kind = (HTML.Tag) o;
    if (kind == HTML.Tag.INPUT || kind == HTML.Tag.SELECT || kind == HTML.Tag.TEXTAREA)
    return new FormView(elem)
    protected void submitData(String data)
    showData(data);
    protected void imageSubmit(String data)
    showData(data);
    // Workaround f�r Bug #4529702
    protected Component createComponent()
    if (getElement().getName().equals("input") &&
    getElement().getAttributes().getAttribute(HTML.Attribute.TYPE).equals("radio"))
    String name = (String) getElement().getAttributes().getAttribute(HTML.Attribute.NAME);
    if (radioGroups.get(name) == null)
    radioGroups.put(name, new ButtonGroup());
    ((JToggleButton.ToggleButtonModel) getElement().getAttributes().getAttribute(StyleConstants.ModelAttribute)).setGroup((ButtonGroup) radioGroups.get(name));
    JComponent comp = (JComponent) super.createComponent();
    // Peque�a mejora visual
    comp.setOpaque(false);
    return comp;
    return super.create(elem);
    //editorPane.setText(FORM_TEXT);
    editorPane.setText(texto);
    getContentPane().add(new JScrollPane(editorPane), BorderLayout.CENTER);
    private void showData(String data) {
         // ergebnis significa resultado
    StringBuffer ergebnis = new StringBuffer("");
    StringTokenizer st = new StringTokenizer(data, "&");
    while (st.hasMoreTokens()) {
    String token = st.nextToken();
    String key = URLDecoder.decode(token.substring(0, token.indexOf("=")));
    String value = URLDecoder.decode(token.substring(token.indexOf("=")+1,token.length()));
    v.add(value);
    ergebnis.append(" "); ergebnis.append(key); ergebnis.append(": "); ergebnis.append(value); ergebnis.append(" ");
    ergebnis.append(" ");
    JOptionPane.showMessageDialog(this, ergebnis.toString());
    public static void main(String[] args) throws Exception {
    JFrame frame = new JFrame ();
    FormSubmission editor = new FormSubmission ();
    frame.getContentPane().add(editor);
    frame.pack();
    frame.show();
    }

  • Swing JEditorPane how to divide a html text in equals pages

    Hi,
    I want to load a html text from a file into a JEditorPane and divide its content in pages with the same number of lines. I want to create a look like in pdf or microsoft word. I found somewhere an example wich create the editor as I want but it is made using shapes and draw them.
    The look is that that I want, but being shapes they aren't editable or selectable.
    Can you give me any ideea how can I make this?
    Thanks in advance!

    You can use this
    http://java-sl.com/Pagination_In_JEditorPane.html
    And this
    http://java-sl.com/JEditorPanePrinter.html
    To see my attempts to achieve the behaviour
    Regards,
    Stas

  • How to retrieve data from the HTML form in the JEditorPane?

    I could quite easily use JEditorPane to render and display a simple HTML file.
    My HTML looks like this:
    <html>
    <head>
    <title> simple form</title>
    </head>
    <body bgcolor="cccccc">
    <center><h1>SURVEY THING</h1>
    </center>
    <form id="survey">
    <p>1.Type something in.</p>
    <textarea cols=25 rows=8>
    </textarea>
    <BR>
    <p>2.Pick ONLY one.</p>
    <input type="radio" name="thing" value="0" Checked> NO choice <BR>
    <input type="radio" name="thing" value="1"> First choice <BR>
    <input type="radio" name="thing" value="2"> Second choice
    <BR>
    <p>3.Pick all you like.</p>
    <input type="checkbox" name="stuff" value="A"> A <BR>
    <input type="checkbox" name="stuff" value="B"> B <BR>
    <input type="checkbox" name="stuff" value="C"> C <BR>
    <input type="submit" value="give data">
    <input type="reset" value="do clensing">
    </form>
    </body>
    </html>
    It gets diplayed fine and I can type in text, select radio buttons (they behave mutualy-exclusive,
    as they should) and check checkboxes.
    The problem I have is with retrieving the values which were entered into the form.
    If I, after editing, try to write the html to the file using HTMLWriter,
    it records the changes I made into the textarea, however all the radio and checkbox selections are lost.
    Maybe the problem is that when I enter the values I do not use any methods like
    insertBeforeStart and so on, but I believe I shouldn't need to use them to populate a form.
    Especially I never change the structure of the HTML.
    Also, when I try to traverse the Element tree and see the input elements attributes,
    I can never see a change in the entered values. However it is probably b/c I am traversing through
    the model and the changes are in the view (just a guess.)
    Anyway, if anybody could direct me onto the right path: how to retrieve the values typed in the form,
    or if it is possible at all in the JEditorPane, I would greatly appreciate.
    thanks
    maciej
    PS. I have seen the answer to a similar question posted some time last year. However, I am trying
    to find a soultion which allows forms/surveys to be built by people who have no java and only basic
    html knwledge. And Axualize way is probably a little bit too "high-tech."

    Maybe helpful for u.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Container;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    public class TestHtmlInput extends JFrame {
         JEditorPane pane=new JEditorPane();
         public TestHtmlInput() {
              super();
              pane.setEditorKit(new HTMLEditorKit());
              pane.setText("<HTML><BODY><FORM>" +
              "<p>1.Input your name.</p>" +
              "<INPUT TYPE='text' name='firstName'>" +
              "<p>2.Input your information.</p>" +
              "<TEXTAREA rows='20' name='StationDescriptions' cols='100'>" +
              "<p>3.Pick ONLY one.</p>" +
              "<input type='radio' name='thing' value='0' Checked> NO choice <BR>" +
              "<input type='radio' name='thing' value='1'> First choice <BR>" +
              "<input type='radio' name='thing' value='2'> Second Choice <BR>" +
              "<p>4.Pick all you like.</p>" +
              "<input type='checkbox' name='stuff' value='A'> A <BR>" +
              "<input type='checkbox' name='stuff' value='B'> B <BR>" +
              "<input type='checkbox' name='stuff' value='C'> C <BR>" +
              "<p>5.Choose your nationality.</p>" +
              "<select name='natio'>" +
              "<option>12</option>" +
              "<option selected>13</option>" +
              "</select>" +
              "</FORM></BODY></HTML>");
              this.getContentPane().add(new JScrollPane(pane));
              JButton b=new JButton("print firstName text");
              b.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        System.out.println("Number of Components in JTextPane: " + pane.getComponentCount());
                        for (int i = 0; i <  pane.getComponentCount(); i++) {
                             //NOTE FOR BELOW: know its a Container since all Components inside a JTextPane are instances of the inner class
                             //ComponentView$Invalidator which is a subclass of the Container Class (ComponentView$Invalidator extends Container)
                             Container c = (Container)pane.getComponent(i);
                             //the component of this containers will be the Swing equivalents of the HTML Form fields (JButton, JTextField, etc.)
                             //Get the # of components inside the ComponentView$Invalidator (the above container)
                             Component swingComponentOfHTMLInputType = c.getComponent(0);
                             //each ComponentView$Invalidator will only have one component at array base 0
                             //DISPLAY OF WHAT JAVA CLASS TYPE THE COMPONENT IS
                             System.out.println(i + ": " + swingComponentOfHTMLInputType.getClass().getName());
                             //this will show of what type the Component is (JTextField, JRadioButton, etc.)
                             if (swingComponentOfHTMLInputType instanceof JTextField) {
                                  JTextField tf = (JTextField)swingComponentOfHTMLInputType;
                                  //downcast and we have the reference to the component now!! :)
                                  System.out.println("  Text: " + tf.getText());
                                  tf.setText("JTextField found!");
                             } else if (swingComponentOfHTMLInputType instanceof JButton) {
                             } else if (swingComponentOfHTMLInputType instanceof JComboBox) {
                                     JComboBox combo = (JComboBox)swingComponentOfHTMLInputType;
                                     System.out.println("  Selected index: " + combo.getSelectedIndex());
                                } else if (swingComponentOfHTMLInputType instanceof JRadioButton) {
                                     JRadioButton radio = (JRadioButton)swingComponentOfHTMLInputType;
                                     System.out.println("  Selected: " + new Boolean(radio.isSelected()).toString());
                             } else if (swingComponentOfHTMLInputType instanceof JCheckBox) {
                                     JCheckBox check = (JCheckBox)swingComponentOfHTMLInputType;
                                     check.setSelected(true);
                                     System.out.println("  Selected: " + new Boolean(check.isSelected()).toString());
                             } else if (swingComponentOfHTMLInputType instanceof JScrollPane) {
                                  JScrollPane pane = (JScrollPane)swingComponentOfHTMLInputType;
                                  for (int j=0; j<pane.getComponentCount(); j++) {
                                       //JTextArea area = (JTextArea)swingComponentOfHTMLInputType.getComponent(0);
                                       Container c2 = (Container)pane.getComponent(j);
                                       for (int k=0; k<c2.getComponentCount(); k++) {
                                            Component c3 = (Component)c2.getComponent(k);
                                            if (c3 instanceof JTextArea) {
                                                 JTextArea area = (JTextArea)c3;
                                                 System.out.println("  " + area.getClass().getName());
                                                 System.out.println("     Text: " + area.getText());
                                                 area.setText("JTextArea found!");
                             } else {
              this.getContentPane().add(b,BorderLayout.SOUTH);
         public static void main(String args[]) {
              TestHtmlInput app = new TestHtmlInput();
              app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              app.setSize( 400, 900 );
              app.setVisible( true );
    }

  • How can I select multiple nodes by standard

    I want to ask how can I modify this example code to enable multiple selection, say if I select node1, system out display node1, then ctr+node2 selection. system out display node1&node2.
    The code below, only display node1, then when I do ctr+node2 selection, system out still display node1.
    I am quite new to JTree, so, please if there is anyone can give a solution?
    Thanks
    * A 1.4 application that requires the following additional files:
    *   TreeDemoHelp.html
    *    arnold.html
    *    bloch.html
    *    chan.html
    *    jls.html
    *    swingtutorial.html
    *    tutorial.html
    *    tutorialcont.html
    *    vm.html
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.UIManager;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreeSelectionModel;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import java.net.URL;
    import java.io.IOException;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    public class TreeDemo extends JPanel
                          implements TreeSelectionListener {
        private JEditorPane htmlPane;
        private JTree tree;
        private URL helpURL;
        private static boolean DEBUG = false;
        //Optionally play with line styles.  Possible values are
    //  "Angled" (the default), "Horizontal", and "None".
        private static boolean playWithLineStyle = false;
        private static String lineStyle = "Horizontal";
        //Optionally set the look and feel.
        private static boolean useSystemLookAndFeel = false;
        public TreeDemo() {
            super(new GridLayout(1,0));
            //Create the nodes.
            DefaultMutableTreeNode top =
                new DefaultMutableTreeNode("The Java Series");
            createNodes(top);
            //Create a tree that allows one selection at a time.
            tree = new JTree(top);
            tree.getSelectionModel().setSelectionMode
                    (TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);---->Cause problem, when press Ctr to multiple select, always the first selected node is returned, which is shown in System out
            //Listen for when the selection changes.
            tree.addTreeSelectionListener(this);
            if (playWithLineStyle) {
                System.out.println("line style = " + lineStyle);
                tree.putClientProperty("JTree.lineStyle", lineStyle);
            //Create the scroll pane and add the tree to it.
            JScrollPane treeView = new JScrollPane(tree);
            //Create the HTML viewing pane.
            htmlPane = new JEditorPane();
            htmlPane.setEditable(false);
            initHelp();
            JScrollPane htmlView = new JScrollPane(htmlPane);
            //Add the scroll panes to a split pane.
            JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
            splitPane.setTopComponent(treeView);
            splitPane.setBottomComponent(htmlView);
            Dimension minimumSize = new Dimension(100, 50);
            htmlView.setMinimumSize(minimumSize);
            treeView.setMinimumSize(minimumSize);
            splitPane.setDividerLocation(100); //XXX: ignored in some releases
                                               //of Swing. bug 4101306
            //workaround for bug 4101306:
            //treeView.setPreferredSize(new Dimension(100, 100));
            splitPane.setPreferredSize(new Dimension(500, 300));
            //Add the split pane to this panel.
            add(splitPane);
        /** Required by TreeSelectionListener interface. */
        public void valueChanged(TreeSelectionEvent e) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                               tree.getLastSelectedPathComponent();
            if (node == null) return;
            Object nodeInfo = node.getUserObject();
            System.out.print("\nMy selection node is"+nodeInfo.toString());
            if (node.isLeaf()) {
                BookInfo book = (BookInfo)nodeInfo;
                displayURL(book.bookURL);
                if (DEBUG) {
                    System.out.print(book.bookURL + ":  \n    ");
            } else {
                displayURL(helpURL);
            if (DEBUG) {
                System.out.println(nodeInfo.toString());
        private class BookInfo {
            public String bookName;
            public URL bookURL;
            public BookInfo(String book, String filename) {
                bookName = book;
                bookURL = TreeDemo.class.getResource(filename);
                if (bookURL == null) {
                    System.err.println("Couldn't find file: "
                                       + filename);
            public String toString() {
                return bookName;
        private void initHelp() {
            String s = "TreeDemoHelp.html";
            helpURL = TreeDemo.class.getResource(s);
            if (helpURL == null) {
                System.err.println("Couldn't open help file: " + s);
            } else if (DEBUG) {
                System.out.println("Help URL is " + helpURL);
            displayURL(helpURL);
        private void displayURL(URL url) {
            try {
                if (url != null) {
                    htmlPane.setPage(url);
                } else { //null url
              htmlPane.setText("File Not Found");
                    if (DEBUG) {
                        System.out.println("Attempted to display a null URL.");
            } catch (IOException e) {
                System.err.println("Attempted to read a bad URL: " + url);
        private void createNodes(DefaultMutableTreeNode top) {
            DefaultMutableTreeNode category = null;
            DefaultMutableTreeNode book = null;
            category = new DefaultMutableTreeNode("Books for Java Programmers");
            top.add(category);
            //original Tutorial
            book = new DefaultMutableTreeNode(new BookInfo
                ("The Java Tutorial: A Short Course on the Basics",
                "tutorial.html"));
            category.add(book);
            //Tutorial Continued
            book = new DefaultMutableTreeNode(new BookInfo
                ("The Java Tutorial Continued: The Rest of the JDK",
                "tutorialcont.html"));
            category.add(book);
            //JFC Swing Tutorial
            book = new DefaultMutableTreeNode(new BookInfo
                ("The JFC Swing Tutorial: A Guide to Constructing GUIs",
                "swingtutorial.html"));
            category.add(book);
            //Bloch
            book = new DefaultMutableTreeNode(new BookInfo
                ("Effective Java Programming Language Guide",
              "bloch.html"));
            category.add(book);
            //Arnold/Gosling
            book = new DefaultMutableTreeNode(new BookInfo
                ("The Java Programming Language", "arnold.html"));
            category.add(book);
            //Chan
            book = new DefaultMutableTreeNode(new BookInfo
                ("The Java Developers Almanac",
                 "chan.html"));
            category.add(book);
            category = new DefaultMutableTreeNode("Books for Java Implementers");
            top.add(category);
            //VM
            book = new DefaultMutableTreeNode(new BookInfo
                ("The Java Virtual Machine Specification",
                 "vm.html"));
            category.add(book);
            //Language Spec
            book = new DefaultMutableTreeNode(new BookInfo
                ("The Java Language Specification",
                 "jls.html"));
            category.add(book);
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            if (useSystemLookAndFeel) {
                try {
                    UIManager.setLookAndFeel(
                        UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {
                    System.err.println("Couldn't use system look and feel.");
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("TreeDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            TreeDemo newContentPane = new TreeDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    you can use the method getSelectionPaths() in the class JTree. It will return an array of all the TreePaths you have selected. Then on each of the TreePath you got use the method getLastPathComponent() to get the nodes which you have selected.
    Hope this solves your problem.

  • How to change the color for HTML words in JEditorPane?

    Hi Sir,
    In the JTextPane , we could change the word's color by using:
    Style style = doc.addStyle("test",null);
    StyleConstants.setForeground(style, Color.red);
    doc.setCharacterAttributes(10,20,syle,true);
    we can change the text into red color,which range is from 10 to 30.
    But how to change the color for HTML words in JEditorPane?

    Hi,
    you can use an AttributeSet to apply the foreground color. Let's say, doc is a HTMLDocument, then SimpleAttributeSet set = new SimpleAttributeSet();
    doc.getStyleSheet().addCSSAttribute(set, CSS.Attribute.COLOR, "#0D0D0D"); would apply a color to a given AttributeSet. The AttributeSet with your color then can be applied to a selected range of text in a JEditorPane by   /**
       * set the attributes for a given editor. If a range of
       * text is selected, the attributes are applied to the selection.
       * If nothing is selected, the input attributes of the given
       * editor are set thus applying the given attributes to future
       * inputs.
       * @param editor  the editor pane to apply the attributes to
       * @param a  the set of attributes to apply
      public void applyAttributes(JEditorPane editor, AttributeSet a) {
        ((HTMLDocument) editor.getDocument()).getStyleSheet().addCSSAttribute(set, CSS.Attribute.COLOR, "#0D0D0D");
        editor.requestFocus();
        int start = editor.getSelectionStart();
        int end = editor.getSelectionEnd();
        if(end != start) {
          doc.setCharacterAttributes(start, end - start, a, false);
        else {
          MutableAttributeSet inputAttributes =
            ((SHTMLEditorKit) editor.getEditorKit()).getInputAttributes();
          inputAttributes.addAttributes(a);
      } Ulrich

Maybe you are looking for