RequestFocus in JEditorPane

Hello Java-Genius!
I would be very happy if someone could tell me why this does not work:
    public void windowGainedFocus(WindowEvent e) {
        editor.requestFocus();
        System.out.println("editor.isVisible() " + editor.isVisible());
        System.out.println("editor.isFocusable() " + editor.isFocusable());
        System.out.println("editor.isDisplayable() " + editor.isDisplayable());   
}This is part of the WindowFocusListener. And I want that editor (JEditorPane) gets the Focus when the Window gets displayed. I read in The AWT Focus Subsystem that a component must be visible, focusable and displayable. All those conditions are met, so I wonder why the editor does not have the focus.......
Any answer will be highly appreciated. Thank you!
Annette

try
editor.requestFocusInWindow();

Similar Messages

  • Find caret position of search text in jEditorPane

    Hi All,
    I am looking for a way to find the Caret position in a jeditor pane for the search text that i supply. The Jeditor pain is setup for text/html and when i find the index of my search text "ANCHOR_d" in the jeditor pane is 27000 something but the caret position is 7495 how do you find the caret position of the search text ??
    Any help is appriciated.
    I am also looking into getting abnchoring to work in the jeditorpane html text but as of yet i have been unsuccessful.
    Kind Regards,
    Wurns

    Search the underlying document, not the editor pane. Play around with this example, which I threw together the other day for a somewhat similar problem with JTextPane involving newlines, and modified for your need.
    Note: Please do not program by exception.import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import javax.swing.JButton;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.text.Document;
    public class SearchEditorPane {
       JFrame frame = new JFrame ("Search JTextPane Test");
       String html = "<HTML><BODY><P>This is <B>some</B>" +
                    " <I>formatted</I>" +
                    " <FONT color=#ff0000>colored</FONT>" +
                    " html.</P>" +
                    "<P>This is a <FONT face=Comic Sans MS>" +
                    "comic <br>\n<br>\nsans ms</FONT> section</P><div>" +
                    "And this is a new division</div>" +
                    "</BODY></HTML>";
       JEditorPane editorPane = new JEditorPane ("text/html", html);
       JPanel panel = new JPanel ();
       JTextField textField = new JTextField (10);
       JButton button = new JButton ("Find");
       Document doc = editorPane.getDocument ();
       void makeUI () {
          editorPane.setText ("<HTML><BODY><P>This is <B>some</B>" +
                " <I>formatted</I>" +
                " <FONT color=#ff0000>colored</FONT>" +
                " html.</P>" +
                "<P>This is a <FONT face=Comic Sans MS>" +
                "comic <br>\n<br>\nsans ms</FONT> section</P><div>" +
                "And this is a new division</div>" +
                "</BODY></HTML>");
          button.addActionListener (new ActionListener () {
             public void actionPerformed (ActionEvent e) {
                // Programming by exception is BAD, don't copy this style
                // This is just to illustrate the solution to the problem at hand
                // (Sorry, uncle-alice, haven't reworked it yet)
                try {
                   Matcher matcher = Pattern.compile (textField.getText ())
                   .matcher (doc.getText (0, doc.getLength ()));
                   matcher.find ();
                   editorPane.setCaretPosition (matcher.start ());
                   editorPane.moveCaretPosition (matcher.end ());
                   editorPane.requestFocus ();
                } catch (Exception ex) {
                   JOptionPane.showMessageDialog (frame, "Not Found!\n" + ex.toString ());
                   //ex.printStackTrace();
          panel.add (textField);
          panel.add (button);
          panel.setPreferredSize (new Dimension (300, 40));
          frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
          frame.setSize (300, 300);
          frame.add (editorPane, BorderLayout.CENTER);
          frame.add (panel, BorderLayout.SOUTH);
          frame.setLocationRelativeTo (null);
          frame.setVisible (true);
       public static void main (String[] args) {
          SwingUtilities.invokeLater (new Runnable () {
             public void run () {
                new SearchEditorPane ().makeUI ();
    }db

  • 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

  • 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());

  • JEditorPane Riddle

    Hello Swing-Experts!
    I another thread I told you about my problems to set the initial font for JEditorPane.
    I now figured out something that is working but I really do not understand why...... Although it is not so important for me to understand everything that I am doing (you know, I often do not understand why I am doing something and I do not mind!) but nevertheless I have some kind of Riddle for you:
    Just execute the following code and please tell me in a way that a housewife can understand it ;-) why the damned and the sucking editor do not work:
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class EditorTestAgain extends JFrame implements ActionListener, CaretListener
        JPanel editorPanel;
        JTextField fontField;
        public EditorTestAgain() {
            editorPanel = new JPanel();
            this.getContentPane().add(editorPanel, BorderLayout.CENTER);
            JPanel buttonPanel = new JPanel();
            JButton b1 = new JButton("damned editor");
            b1.addActionListener(this);
            buttonPanel.add(b1);
            JButton b2 = new JButton("JEditorPane sucks!");
            b2.addActionListener(this);
            buttonPanel.add(b2);
            JButton b3 = new JButton("Working!!!!!!!");
            b3.addActionListener(this);
            buttonPanel.add(b3);
            JButton b4 = new JButton("Working again!!!!!");
            b4.addActionListener(this);
            buttonPanel.add(b4);
            JButton b5 = new JButton("sick editor");
            b5.addActionListener(this);
            buttonPanel.add(b5);
            this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
            this.fontField = new JTextField(60);
            this.getContentPane().add(fontField, BorderLayout.NORTH);
            this.setSize(800, 400);
            this.setVisible(true);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public static void main(String[] args) {
            EditorTestAgain test = new EditorTestAgain();
        private JEditorPane createEditor() {
            JEditorPane editor = new JEditorPane("text/html", "");
            editor.setEditorKit(new HTMLEditorKit());
            Font defaultFont = new Font("Verdana" , Font.PLAIN, 24);
            HTMLDocument doc = new HTMLDocument();
            Element rootElement = doc.getDefaultRootElement();
            SimpleAttributeSet s = new SimpleAttributeSet();
            StyleConstants.setFontFamily(s, defaultFont.getFamily());
            StyleConstants.setFontSize(s, defaultFont.getSize());
            doc.setCharacterAttributes(rootElement.getStartOffset(),
                    rootElement.getEndOffset()-rootElement.getStartOffset(), s, true);
            editor.setDocument(doc);
            return editor;
        private JEditorPane createWorkingEditor2() {
            JEditorPane editor = new JEditorPane("text/html", "");
            editor.setEditorKit(new HTMLEditorKit());
            Font defaultFont = new Font("Verdana" , Font.PLAIN, 24);
            editor.setDocument(new AnnettesHTMLDocument(defaultFont));
            return editor;
        private JEditorPane createDamnedEditor() {
            JEditorPane editor = new JEditorPane("text/html", "");
            editor.setEditorKit(new HTMLEditorKit());
            Font defaultFont = new Font("Verdana" , Font.PLAIN, 24);
            editor.setDocument(new AnnettesHTMLDocument2(defaultFont));
            return editor;
        private JEditorPane createSuckingEditor() {
            JEditorPane editor = new JEditorPane("text/html", "");
            editor.setEditorKit(new HTMLEditorKit());
            Font defaultFont = new Font("Verdana" , Font.PLAIN, 24);
            HTMLDocument doc = (HTMLDocument)editor.getDocument();
            Element rootElement = doc.getDefaultRootElement();
            SimpleAttributeSet s = new SimpleAttributeSet();
            StyleConstants.setFontFamily(s, defaultFont.getFamily());
            StyleConstants.setFontSize(s, defaultFont.getSize());
            doc.setCharacterAttributes(rootElement.getStartOffset(),
                    rootElement.getEndOffset()-rootElement.getStartOffset(), s, true);
            return editor;
        public void caretUpdate(CaretEvent e) {
         JEditorPane editor = (JEditorPane)e.getSource();
            this.showFont(editor);
        public void actionPerformed(ActionEvent e) {
            this.editorPanel.removeAll();
            JEditorPane editor = null;
            if (e.getActionCommand().equals("Working again!!!!!")) {
                editor = createWorkingEditor2();
            else if (e.getActionCommand().equals("damned editor")) {
                editor = createDamnedEditor();
            else if (e.getActionCommand().equals("JEditorPane sucks!")) {
                editor = createSuckingEditor();
            else if (e.getActionCommand().equals("Working!!!!!!!")) {
                editor = createEditor();
            else if (e.getActionCommand().equals("sick editor")) {
                editor = new ChickenPox();
            if (editor != null) {
                editor.setPreferredSize(new Dimension(500, 300));
                this.editorPanel.add(editor);
                this.editorPanel.revalidate();
                this.editorPanel.repaint();
                editor.addCaretListener(this);
                editor.requestFocus();
                this.showFont(editor);
        private void showFont(JEditorPane editor) {
            if (editor instanceof ChickenPox) {
                this.fontField.setText("So you want me to tell you something " +
                        "about my font? Do not bother me with that kind of stuff, " +
                        "right?!?! Just open your eyes and see!!!!!");
            else {
                HTMLDocument doc = (HTMLDocument)editor.getDocument();
                int caretPosition = editor.getCaretPosition();
                Element element = doc.getCharacterElement(caretPosition);
                String fontFamily = StyleConstants.getFontFamily(element.getAttributes());
                int fontSize = StyleConstants.getFontSize(element.getAttributes());
                this.fontField.setText("font at caretPosition " + caretPosition + ": " +
                    fontFamily + " " + fontSize);
        class AnnettesHTMLDocument extends HTMLDocument {
            Font defaultFont;
            public AnnettesHTMLDocument(Font df) {
                this.defaultFont = df;
                Element rootElement = this.getDefaultRootElement();
                SimpleAttributeSet s = new SimpleAttributeSet();
                StyleConstants.setFontFamily(s, defaultFont.getFamily());
                StyleConstants.setFontSize(s, defaultFont.getSize());
                this.setCharacterAttributes(rootElement.getStartOffset(),
                        rootElement.getEndOffset()-rootElement.getStartOffset(), s, true);
        class AnnettesHTMLDocument2 extends HTMLDocument {
            Font defaultFont;
            public AnnettesHTMLDocument2(Font df) {
                this.defaultFont = df;
            public Font getFont(AttributeSet attr) {
                String family = (String) attr.getAttribute(StyleConstants.FontFamily);
                if (family == null) {
                    return this.defaultFont;
                return super.getFont(attr);
        class ChickenPox extends JEditorPane {
                public ChickenPox() {
              this.setContentType( "text/html" );
                public void paint(Graphics g) {
                    super.paint(g);
                    Dimension d = this.getSize();
                    Random r = new Random();
                    for (int i=0; i<500; i++) {
                        float f = r.nextFloat();
                        g.setColor(Color.RED);
                        g.fillOval(new Double(r.nextFloat()*d.getWidth()).intValue(),
                                new Double(r.nextFloat()*d.getHeight()).intValue(), 2, 2);
    }And for all others who might be interested what solution DOES work:
        private JEditorPane createEditor() {
            JEditorPane editor = new JEditorPane("text/html", "");
            editor.setEditorKit(new HTMLEditorKit());
            Font defaultFont = new Font("Verdana" , Font.PLAIN, 24);
            HTMLDocument doc = new HTMLDocument();
            Element rootElement = doc.getDefaultRootElement();
            SimpleAttributeSet s = new SimpleAttributeSet();
            StyleConstants.setFontFamily(s, defaultFont.getFamily());
            StyleConstants.setFontSize(s, defaultFont.getSize());
            doc.setCharacterAttributes(rootElement.getStartOffset(),
                    rootElement.getEndOffset()-rootElement.getStartOffset(), s, true);
            editor.setDocument(doc);
            return editor;
        }while it is really absurd and stupid to do it this way:
        private JEditorPane createSuckingEditor() {
            JEditorPane editor = new JEditorPane("text/html", "");
            editor.setEditorKit(new HTMLEditorKit());
            Font defaultFont = new Font("Verdana" , Font.PLAIN, 24);
            HTMLDocument doc = (HTMLDocument)editor.getDocument();
            Element rootElement = doc.getDefaultRootElement();
            SimpleAttributeSet s = new SimpleAttributeSet();
            StyleConstants.setFontFamily(s, defaultFont.getFamily());
            StyleConstants.setFontSize(s, defaultFont.getSize());
            doc.setCharacterAttributes(rootElement.getStartOffset(),
                    rootElement.getEndOffset()-rootElement.getStartOffset(), s, true);
            return editor;
        }Annette

    Compilation .... OK
    Running the program .... OK
    With me! All the button is working, and with the sick editor i got a nice message
    (So you want me to tell you something about my font? Do not bother me with that kind of stuff, right?!?! Just open your eyes and see!!!!!)

  • Cut, Copy and Paste + JEditorPane

    I am currently working on a text editor and i have now come to the cut, copy and paste "functions". When i try to compile my code i get:
    1. ERROR in MyMenu.java (at line 42)
    GUI.textarea.cut();
    ^^^
    The method cut() is undefined for the type JEditorPane
    2. ERROR in MyMenu.java (at line 47)
    GUI.textarea.copy();
    ^^^^
    The method copy() is undefined for the type JEditorPane
    3. ERROR in MyMenu.java (at line 51)
    GUI.textarea.paste();
    ^^^^^
    The method paste() is undefined for the type JEditorPane
    The code:
                             else if(event.getActionCommand().equals("Klipp ut")){
                             GUI.textarea.requestFocus();
                               GUI.textarea.cut();
                             else if(event.getActionCommand().equals("Kopiera")){
                             GUI.textarea.requestFocus();
                               GUI.textarea.copy();
                             else if(event.getActionCommand().equals("Klistra in")){
                             GUI.textarea.requestFocus();
                               GUI.textarea.paste();
                             }

    That didn't help me at all. I am trying to run the copy, paste and cut actions from my JMenubar. You can see my Jmenubar class code here.
    // Importerar det n�dv�ndiga
    import java.awt.*; import java.awt.event.*; import javax.swing.*;
    public class MyMenu extends JMenuBar
       // Arkivmenyn
       String fileItems[] = new String [] {"Nytt","�ppna","Spara","Spara som...","Avsluta"};
       char fileShortcuts[] = {'N','O','S','A','P','C','x'};
       char fileAccelerators[] = {};
       // Redigeramenyn
       String editItems[] = new String [] {"�ngra","G�r om","Klipp ut","Kopiera","Klistra in",
          "Rensa","Markera allt"};
       char editShortcuts[] = {'U','R','t','C','P','l','S'};
       char editAccelerators[] = {'Z','Y','X','C','V','\u0000','A'};
       // Konstruktorn
       MyMenu()
            // Namn till Menynraden
                   JMenu fileMenu = new JMenu("Arkiv");
                   JMenu editMenu = new JMenu("Redigera");
                   JMenu helpMenu = new JMenu("Hj�lp");
         // Kollar efter vilken meny som anv�ndaren g�r in p�
              ActionListener printListener = new ActionListener()
                           public void actionPerformed(ActionEvent event)
                             // Detta skall h�nda n�r anv�ndaren g�r in p� Avsluta
                             if(event.getActionCommand().equals("Avsluta")){System.exit(0);}
                             // Nytt
                             else if(event.getActionCommand().equals("Nytt") || event.getActionCommand().equals("Rensa")){
                                  GUI.textarea.setText("");
                             else if(event.getActionCommand().equals("Klipp ut")){
                               GUI.textarea.cut();
                             else if(event.getActionCommand().equals("Kopiera")){
                               GUI.textarea.copy();
                             else if(event.getActionCommand().equals("Klistra in")){
                               GUI.textarea.paste();
                             else if(event.getActionCommand().equals("�ppna")){
                               MyBrowser myBrowser = new MyBrowser();
                                 myBrowser.setVisible(false);
                             // Annars skall denna kodsnutt k�ras
                             else {System.out.println("Menu item["+event.getActionCommand()+"[pressed!");}
         // For-sats f�r att skapa Arkivmenyn
         for (int i=0;i<fileItems.length;i++)
            JMenuItem item = new JMenuItem(fileItems, fileShortcuts[i]);
         item.addActionListener(printListener);
         fileMenu.add(item);
         // Redigera-menyn
    for (int i=0;i<editItems.length;i++)
         JMenuItem item = new JMenuItem(editItems[i], editShortcuts[i]);
    if (editAccelerators[i] > ' ') // M�ste l�ggas till
    {item.setAccelerator(KeyStroke.getKeyStroke(editAccelerators[i],
    Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),false));}
         item.addActionListener(printListener);
         editMenu.add(item);
         // L�gger in tv� linjer i Redigeramenyn p� plats 2 och 9
    editMenu.insertSeparator(2);
    // L�gger till de skapade undermenyerna i menylisten
    add(fileMenu); add(editMenu); add(helpMenu);

  • Set default font of JEditorPane ?????

    Hi java gang!
    I am completely lost! I hope that you will be patient with me because I must be doing something very stupid.
    I just want to set the default font of my JEditorPane.
    I tried
    editor.setFont(new Font("SansSerif", Font.PLAIN, 20));
    editor.setText("<html>  <head> </head> " +
                              "<body><font face='sans serif' size='20'> </font></body>");
    UIManager.put("EditorPane.font", new javax.swing.plaf.FontUIResource("SansSerif", Font.PLAIN, 24));without success.
    And to not disturb for example Mr. camickr I created a SSCCE ;-)
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import java.awt.*;
    import java.awt.event.*;
    public class EditorTest extends JFrame implements ActionListener {
        JPanel editorPanel;
        public EditorTest() {
            editorPanel = new JPanel();
            this.getContentPane().add(editorPanel, BorderLayout.CENTER);
            JPanel buttonPanel = new JPanel();
            JButton b1 = new JButton("setFont");
            b1.addActionListener(this);
            buttonPanel.add(b1);
            JButton b2 = new JButton("html");
            b2.addActionListener(this);
            buttonPanel.add(b2);
            JButton b3 = new JButton("html2");
            b3.addActionListener(this);
            buttonPanel.add(b3);
            JButton b4 = new JButton("UIManager");
            b4.addActionListener(this);
            buttonPanel.add(b4);
            this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
            this.setPreferredSize(new Dimension(600,400));
            this.pack();
            this.setVisible(true);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public static void main(String[] args) {
            EditorTest test = new EditorTest();
        public void actionPerformed(ActionEvent e) {
            this.editorPanel.removeAll();
            JEditorPane editor = null;
            if (e.getActionCommand().equals("setFont")) {
                editor = createEditorUsingSetFont();
            else if (e.getActionCommand().equals("html")) {
                editor = createEditorUsingHtml();
            else if (e.getActionCommand().equals("html2")) {
                editor = createEditorUsingHtml2();
            else if (e.getActionCommand().equals("UIManager")) {
                editor = createEditorUsingUIManager();
            if (editor != null) {
                this.editorPanel.add(editor);
                this.editorPanel.revalidate();
                this.editorPanel.repaint();
                editor.requestFocus();
                this.printFontAtCaret(editor);
        private JEditorPane createEditorUsingSetFont() {
            JEditorPane editor = new JEditorPane("text/html", "");
            editor.setEditorKit(new HTMLEditorKit());
            editor.setFont(new Font("SansSerif", Font.PLAIN, 20));
            editor.setPreferredSize(new Dimension(500, 300));
            return editor;
        private JEditorPane createEditorUsingHtml() {
            JEditorPane editor = new JEditorPane("text/html", "<html>  <head> </head>" +
                    "  <body><font face='sans serif' size='20'> </font></body>");
            editor.setEditorKit(new HTMLEditorKit());
            editor.setPreferredSize(new Dimension(500, 300));
            return editor;
        private JEditorPane createEditorUsingHtml2() {
            JEditorPane editor = new JEditorPane("text/html", "");
            editor.setEditorKit(new HTMLEditorKit());
            editor.setText("<html>  <head> </head>  <body>" +
                    "<font face='sans serif' size='20'> </font></body>");
            editor.setPreferredSize(new Dimension(500, 300));
            return editor;
        private JEditorPane createEditorUsingUIManager() {
            System.out.println(UIManager.get("EditorPane.font"));
            UIManager.put("EditorPane.font",
                    new javax.swing.plaf.FontUIResource("SansSerif", Font.PLAIN, 24));
            System.out.println(UIManager.get("EditorPane.font"));
            JEditorPane editor = new JEditorPane("text/html", "");
            editor.setEditorKit(new HTMLEditorKit());
            editor.setPreferredSize(new Dimension(500, 300));
            return editor;
        private void printFontAtCaret(JEditorPane editor) {
            HTMLDocument doc = (HTMLDocument)editor.getDocument();
            Element element = doc.getCharacterElement(editor.getCaretPosition());
            System.out.println("fontSize " +
                    StyleConstants.getFontSize(element.getAttributes()));
            System.out.println("fontFamily " +
                    StyleConstants.getFontFamily(element.getAttributes()));
    }Please notice that I did non forget to use code format tags! At least one thing I can do right today........
    Annette

    This is really shocking!
    But you may take a look at this:
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class CamicksEditorTest extends JFrame implements ActionListener, CaretListener
        JPanel editorPanel;
        public CamicksEditorTest() {
            editorPanel = new JPanel();
            this.getContentPane().add(editorPanel, BorderLayout.CENTER);
            JPanel buttonPanel = new JPanel();
            JButton b1 = new JButton("setFont");
            b1.addActionListener(this);
            buttonPanel.add(b1);
            JButton b2 = new JButton("html");
            b2.addActionListener(this);
            buttonPanel.add(b2);
            JButton b3 = new JButton("html2");
            b3.addActionListener(this);
            buttonPanel.add(b3);
            JButton b4 = new JButton("UIManager");
            b4.addActionListener(this);
            buttonPanel.add(b4);
            JButton b5 = new JButton("Diagnosis");
            b5.addActionListener(this);
            buttonPanel.add(b5);
            this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
    //        this.setPreferredSize(new Dimension(600,400));
    //        this.pack();
              this.setSize(600, 400);
            this.setVisible(true);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public static void main(String[] args) {
            CamicksEditorTest test = new CamicksEditorTest();
        public void actionPerformed(ActionEvent e) {
            this.editorPanel.removeAll();
            JEditorPane editor = null;
            if (e.getActionCommand().equals("setFont")) {
                editor = createEditorUsingSetFont();
            else if (e.getActionCommand().equals("html")) {
                editor = createEditorUsingHtml();
            else if (e.getActionCommand().equals("html2")) {
                editor = createEditorUsingHtml2();
            else if (e.getActionCommand().equals("UIManager")) {
                editor = createEditorUsingUIManager();
            else if (e.getActionCommand().equals("Diagnosis")) {
                editor = new ChickenPox();
                editor.setPreferredSize(new Dimension(500, 300));
            if (editor != null) {
                this.editorPanel.add(editor);
                this.editorPanel.revalidate();
                this.editorPanel.repaint();
                editor.addCaretListener(this);
                editor.requestFocus();
    //            this.printFontAtCaret(editor);
        private JEditorPane createEditorUsingSetFont() {
            JEditorPane editor = new JEditorPane("text/html", "");
    //        editor.setEditorKit(new HTMLEditorKit());
            editor.setFont(new Font("SansSerif", Font.PLAIN, 20));
            editor.setPreferredSize(new Dimension(500, 300));
            return editor;
        private JEditorPane createEditorUsingHtml() {
            JEditorPane editor = new JEditorPane("text/html", "<html>  <head> </head>" +
                    "  <body><font face='sans serif' size='20'>HTML1</font></body></html>");
    //        editor.setEditorKit(new HTMLEditorKit());
            editor.setPreferredSize(new Dimension(500, 300));
            return editor;
        private JEditorPane createEditorUsingHtml2() {
    //        JEditorPane editor = new JEditorPane("text/html", "");
            JEditorPane editor = new JEditorPane();
              editor.setContentType( "text/html" );
    //        editor.setEditorKit(new HTMLEditorKit());
            editor.setText("<html><head> </head><body>" +
                    "before <font face='sans serif' size='8'>HTML2</font> after</body></html>");
            editor.setPreferredSize(new Dimension(500, 300));
            return editor;
        private JEditorPane createEditorUsingUIManager() {
            System.out.println(UIManager.get("EditorPane.font"));
            UIManager.put("EditorPane.font",
                    new javax.swing.plaf.FontUIResource("SansSerif", Font.PLAIN, 24));
            System.out.println(UIManager.get("EditorPane.font"));
            JEditorPane editor = new JEditorPane("text/html", "");
    //        editor.setEditorKit(new HTMLEditorKit());
            editor.setPreferredSize(new Dimension(500, 300));
            return editor;
         public void caretUpdate(CaretEvent e)
              JEditorPane editor = (JEditorPane)e.getSource();
            HTMLDocument doc = (HTMLDocument)editor.getDocument();
            Element element = doc.getCharacterElement(editor.getCaretPosition());
            System.out.println("fontSize " +
                    StyleConstants.getFontSize(element.getAttributes()));
            System.out.println("fontFamily " +
                    StyleConstants.getFontFamily(element.getAttributes()));
            class ChickenPox extends JEditorPane {
                public ChickenPox() {
              this.setContentType( "text/html" );
                public void paint(Graphics g) {
                    super.paint(g);
                    Dimension d = this.getSize();
                    Random r = new Random();
                    for (int i=0; i<500; i++) {
                        float f = r.nextFloat();
                        g.setColor(Color.RED);
                        g.fillOval(new Double(r.nextFloat()*d.getWidth()).intValue(),
                                new Double(r.nextFloat()*d.getHeight()).intValue(), 2, 2);
    }So as you can see very easily when you click the Button Diagnosis: My JEditorPanes are just infected with chickenpox (like my kids are.....). So maybe this can explain the strange behavior... And if you run the sample code, just be prepared that your JEditorPanes will be infected, too, in about two weeks.....
    all joking aside: Maybe someone knows what I could do? I will appreciate any answer very much! Thanks a lot!

  • JEditorPane loses caret

    I have two panels (error message and source code). I click on a message and then I load and scroll the source (in a JEditorPane) to the line with the error. But sometimes (JDK1.3.1) the caret disappears. If I then focus another window and then focus the source window back, the caret reappears. I have tried refocusing the JEditorPane using swing invokeLater. I checked the bug database but no luck.

    Found the answer so I'm putting it here for next guy. 1) make sure the JEditorPane gets the focus back (with a requestFocus in an invokeLater section). 2) after setting focus, do a getCaret().setVisible( true ).

  • Repaint a JEditorPane after inserting data in the Document

    Hi,
    I have a button that inserts some text in a Document using the method insert(int offset, ElementSpec[] data)After that insert, the View recalculates the heights of the text lines, but they don't get refreshed on the JEditorPane. I have to manually insert a new line to make the JEditorPane get updated with the new line height.
    I have tried using invalidate() and repaint() but nothing happens. Is there another way to refresh the contents of the JEditorPane?
    Thanks!!

    revalidate() didn't work. I still have to press "enter" in any part of the document in order to have the line height changed. The method that recalculates the height of the line is View.getPreferredSpan(int) but it isn't called until I insert a new line by pressing enter.
    I think now it's not a repainting issue, I move the window outside the screen and back again and it still doesn't update. The problem is that getPreferredSpan() is not called when it repaints.
    Thanks for your response. I will try to find out how to have the view's size recalculated when I insert content.

  • How to insert hyperlinks in RTF document shown in JEditorPane?

    This is a compound question so bear with me on this one :)
    What I need is to insert an hyperlink in a JEditorPane; Store it as RTF code; Retrieve it; Show it and click on it to go the the destination.
    1) So, first question, is there some method to automatically add the hyperlink and will it be saved in RTF with RTFEditorKit? (I'm actually using AdvancedRTFEditorKit but an answer to either will be enough)
    2) I tried a method that adds what appears as a link but the document that is stored doesn't have the necessary RTF codes, only the formatting that makes it look like a link. I also checked the actual RTF codes I'd need to add and they seem easy to do. So, is there a way to add the actual underlying RTF codes to the document while it's in the JEditorPane?
    I know the question(s) isn't too specific, if you can shed some light over the whole thing and point me in the right direction, it'd be great!

    Just a follow up to my own question. I found a way to answer my question 2) and I'm now storing the rtf code for hyperlinks. Now, when I show the document in JEditorPane with RTFEditorKit, I get the name of the hyperlink with no formatting indicating that it's a hyperlink.
    Example. The link "http://www.google.com" with the name "Google", only shows "Google" in plain text.
    Is it because the components I'm using don't support hyperlinks from RTF files even though they're supported from HTML files?
    Is there any way you can see this working? Is it possible to include something inside the JEditorPane that the user can click, instead of the hyperlink?

  • HTML file is not being shown properly in the JEditorPane

    Hi,
    I am using JEditorPane to display an HTML file from the local disk. This HTML file contains the html tables. Now when this file is getting displayed in the JEditorPane, one top row grid is not being displayed in the editor pane. content of the row is there...but the column grid is missing. All other rows and columns are being shown but the first row-column grid which contains the heading for column.
    Also when I m printing the content of this JEditorPane using Java Print API then no grid is being printed on the paper. content is coming properly but no table grids. when i have taken the print out of the original html file from the browser then table grids are being printed out properly.
    Please do help me out in showing the HTML file in the JEditorPane properly and printing the same.
    Many Thanks,
    gshankar

    Hi,
    JEditorPane renders HTML with many limitations.
    You can use JDIC for the same. refer: jdic.dev.java.net
    But JDIC does not work on windows 98.
    Anand

  • Highlighting text in JEditorPane using HTMLEditorPane

    I am using JEditorPane extending HTMLEditorkit. In the HTMLEditorkit when we use the span tag for highlighting the text of a line, it is just not showing it. It starts the color and ends it there and then. It looks like a small dot and doesnot spans the whole line.
    Is this a bug or something in JAVA 1.3.1. If anyone of you knows how to do it please let me know.
    I need it for a project which has a deadline.
    Thanks.

    JEditorPane is not rendering and HTMLDocument.HTMLReader is not reading the SPAN tag. In other words, the SPAN tag is not supported in Java. You can still use it by overriding the mentioned classes. My application SimplyHTML gives an example of how this can be done. Please visit http://www.lightdev.com/dev/sh.htm
    Ulrich

  • How to modify text insertion position in HTML in a JEditorPane

    Hi all,
    Thanks in advance if anyone knows the type of code I need to look at to solve my problem.
    It involves the insertion point (in the actual HTML) when editing text in a JEditorPane using type html/txt.
    for example, lets say you start to add text by typing in a JEditorPane which already contains some text.
    The html is:
    <html><head></head>
    <body>
    <span>inside</span>
    </body>
    </html>
    which represents visually:
    inside
    The user places the caret (by pointing and clicking the mouse) after the word 'inside'.
    The user types the word 'outside'.
    The resulting html will look like this:
    <html><head></head>
    <body>
    <span>insideoutside</span>
    </body>
    </html>
    I would very much prefer it to look like this:
    <html><head></head>
    <body>
    <span>inside</span>outside
    </body>
    </html>
    Does anyone know how to influence the position of insertion in this way?
    Thanks again,
    sean

    Success!!!
    In a tiny bit of a hacky way.
    I will share my path to success. Though I am sure it could be improved. The solution (except for the minor hack to get it to work at all) is quite simple.
    And it did indeed involve the use of the DocumentFilter.
    So, to recap, My objective was to prevent the user from causing the addition of text within a certain span tag in my HTML when editing visual through a JEditorPane.
    Specifically, in my HTML I have a number of span tags identified through a type attribute. My span tags look like this:
    <span type="reserved">hello</span>
    I wanted to prevent the user from being able to type (visually) to cause either this:
    <span type="reserved">next text hello</span>
    or
    <span type="reserved">hello new text</span>
    or
    <span type="reserved">he new text llo</span>
    Initially, I had used a Caret listener, and moved the caret along, which, besides being hugely ugly, wouldn't fix the main problem of, even when the user starts typing after the word 'hello' on the visual pane, the text would be appended within the span tag, and not outside. Even though if I were to check my position (with the following code) I would be told it wasn't associated with the span attribute at all
              Element elem = hdoc.getCharacterElement(pos);
              AttributeSet a = elem.getAttributes();
              AttributeSet spanAttributeSet = (AttributeSet)a.getAttribute(HTML.Tag.SPAN);
              // if spanAttributeSet is not null, then we properly found ' a span '.
              // now we need to discover if it is one of OUR spans
              if (spanAttributeSet != null)
                    { // blah .... do something
                    }Regardless of what it told me with the above code, if i were to type in at that position (just after the hello) it would be added to the span tag. Which is what I didn't want.
    But the discovery of the DocumentFilter was what I needed to look at. Although, I had a very strange problem of having to reassign the document filter several times to the editorPane (later checks would see it as null). I don't know why I have this problem, but I have made a work-around by ensuring the DocumentFilter is still assigned by reassigning it every time the user moves the caret in the editorpane. Not nice, but prevents my filter from being ignored.
    The real solution:
    Using the DocumentFilter, I was able to solve both my problems of , not allowing the user to type inside the word 'hello', and preventing the text typed after the 'hello' being appended inside the span tag by the Document model.
    This is my code:
               myFilter = new DocumentFilter(){
                    public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attrs) throws BadLocationException
                         System.out.println("in insert string");
                           if (isCaretOnReservedObject((HTMLDocument)fb.getDocument(), offset))
                                throw new BadLocationException("Reserved position", offset);
                           else
                                    Object val = attrs.getAttribute(HTML.Attribute.TYPE);
                                if (val!=null && val.equals("reserved"))
                                     super.insertString(fb, offset, string, null);
                                else
                                     super.insertString(fb, offset, string, attrs);
                    @Override
                    public void remove(DocumentFilter.FilterBypass fb,
                            int offset,
                            int length)
                     throws BadLocationException
                         super.remove(fb, offset, length);
                      public void replace(DocumentFilter.FilterBypass fb,
                             int offset,
                             int length,
                             String text,
                             AttributeSet attrs)
                      throws BadLocationException
                           if (isCaretOnReservedObject((HTMLDocument)fb.getDocument(), offset))
                                throw new BadLocationException("Reserved position", offset);
                           else
                                    Object val = attrs.getAttribute(HTML.Attribute.TYPE);
                                if (val!=null && val.equals("reserved"))
                                     super.replace(fb, offset, length, text, null);
                                else
                                     super.replace(fb, offset, length, text, attrs);
               ((AbstractDocument)this.getInternalJEditorPane().getDocument()).setDocumentFilter(myFilter);
         protected boolean isCaretOnReservedObject(HTMLDocument hdoc, int pos)
              boolean retval = false;
              Element elem = hdoc.getCharacterElement(pos);
              AttributeSet a = elem.getAttributes();
              AttributeSet spanAttributeSet = (AttributeSet)a.getAttribute(HTML.Tag.SPAN);
              // if spanAttributeSet is not null, then we properly found ' a span '.
              // now we need to discover if it is one of OUR spans
              if (spanAttributeSet != null)
                   Object type = spanAttributeSet.getAttribute(HTML.Attribute.TYPE);
                   if (type != null && type.equals("reserved"))
                        // for our logging, we get the ref, which holds the source
                        // of our value later
                        System.out.println(elem + ": the value is: " + spanAttributeSet.getAttribute("ref"));
                        retval = true;
              return retval;
         }And now, when I attempt to type on the word 'hello', nothing happens (great!), and when I type after it, it is not assigned the span tag attribute, and we later find it (when outputting html) at the outside of the span tag.
    I don't know if there is a better way to do this, but it looks and works fairly cleanly so far.
    And thanks to stas for your reply...... Maybe this is what you meant. . it certainly was the attributes I needed to fiddle with here, and it gave me an extra hint of what to look for when researching the problem.
    Edited by: svaens on Sep 28, 2009 6:56 PM
    forgot to add dependency to code snippet
    Edited by: svaens on Sep 28, 2009 9:34 PM
    fix bug

  • 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();
    }

  • How can I create JEditorPane which scrolls to the bottom on every resize?

    JRE 1.3.0
    Included a simple frame with the only control - JEditorPane (contained within JScrollPane). Every time scroll pane size changes, attempt to scroll down to the end of JEditorPane is made.
    The problem is: although everything works 9 times of 10, sometimes editor is scrolled almost to the end, sometimes - to the very top. On the next resize editor is scrolled correctly.
    I think, there are some delayed layout recalculations inside SWING which prevent JEditorPane and/or JScrollPane from knowing actual size.
    Is it possible to force JEditorPane+JScrollPane pair to update dimensions? ( explicit call to doLayout() does not fix anything )
    Thanks
    public class TestFrame extends JFrame
    BorderLayout borderLayout1 = new BorderLayout();
    JScrollPane jScrollPane1 = new JScrollPane();
    JEditorPane jEditorPane1 = new JEditorPane();
    public TestFrame()
    try
    jbInit();
    catch(Exception e)
    e.printStackTrace();
    private void jbInit() throws Exception
    this.getContentPane().setLayout(borderLayout1);
    jEditorPane1.setContentType("text/html");
    jEditorPane1.setText("test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test ");
    jScrollPane1.addComponentListener(new java.awt.event.ComponentAdapter()
    public void componentResized(ComponentEvent e)
    jScrollPane1_componentResized(e);
    this.getContentPane().add(jScrollPane1, BorderLayout.CENTER);
    jScrollPane1.getViewport().add(jEditorPane1, null);
    void jScrollPane1_componentResized(ComponentEvent e)
    Dimension size = jEditorPane1.getPreferredSize();
    jEditorPane1.scrollRectToVisible( new Rectangle(0, size.height, 0, 0) );
    System.out.println("preferred height=" + size.height);
    }

    Seen this thread?
    Return to previously viewed page

Maybe you are looking for