JScrollPane (containing an expanding JTextPane)

I am writing a chatroom program using Swing, so I have this JScrollPane wrapping a JTextPane where all the messages (conversations) are displayed. When a new message comes up, the program inserts it at the end of the JTextPane's StyledDocument. This is when some strange things happen (regardless of where is the JScrollPane's view). In the beginning, it scrolls to the very bottom automatically whenever a new message is inserted. However, sometimes, after I do some random manual scrolling, it just stays at the same location regardless if there is a new message inserted. This is obviously not what I would want for my chatroom.
Instead, I want these behaviours when a new message is added:
1) The JScrollPane will scroll to the bottom if it was already at the bottom before the message was added.
2) The JScrollPane's view will stay at the same location if the user was viewing something in the middle of the JTextPane (not at the bottom).
Please tell me how I can do this. Thanks!

Thanks for the link which has very nice info on auto-scrolling.
However, that only solved half of my problems.
I don't want it to scroll when the user is viewing somewhere not at the bottom of the JScrollPane, which was the case (2) that I was describing. Can you suggest how I can do that?

Similar Messages

  • JScrollPane containing JPanel HELP!

    Hi again,
    I'll try my luck again!
    Ok, I have a JPanel that uses a GridBagLayout with 3 columns and many rows. Each row is of the form:
    [JLabel][JTextField][JButton]
    Ok. Since I have many of these rows, and my application should be a constant size, I need to somehow make you able to scroll down the list of these labels,textfields and buttons - to the one you want. I have tried making the containing JPanel the viewport of a JScrollPane, however, when I only have a couple of rows of labels, textfields, and buttons, each expands to fit the viewport size - and they turn out looking really dumb.
    How can I get it so that the labels, textfields and buttons are only the height of the text in each?
    Please please, please, please help me.
    sincerely, Edd.

    Chenge the weight (x&y) in the GridBagConstraints of the components you don't want to expand to 0.0. Change the fill to GridBagConstraints.NONE.

  • Excel Export of a Report containing Subreports expands first subreport, but not subsequent ones

    I have a report built in SSRS 2008 that contains a subreport that is made visible by toggling an item on the row of the parent report that contains the subreport.
    When I export the report to Excel it works great except that the first subreport is always expanded in Excel and the ability to toggle it is not given in Excel. All subreports are not visible (toggled as not shown) when exporting, yet the first subreport is always shown in Excel as an expanded value with no ability to toggle in Excel. All the other subreports are exported correctly as not visible with a plus sign next to the parent row to expand it.
    Any ideas what might cause this?

    I've have the same issue but haven't found a solution yet. Do you remember if you ever solved your problem?

  • Why is my container div expanding past the 1170px max width in preview mode?

    Why is my container div div expanding past the 1170px max width in preview mode?
    Thanks again,
    Marc

    #wrapper #leftside img {
    float: left;
    width: 399px;
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    ==================
    "Ruby7829" <[email protected]> wrote in
    message
    news:gdkr52$m6b$[email protected]..
    > I'm trying to get the image on my homepage (which is 320
    x 214) to sit
    > inside
    > my "leftside" div (which is 380 width). Why is it
    expanding to 380 px if
    > I put
    > it in it's own div which is 320 px? What am I doing
    wrong? Should I not
    > have
    > nested divs?
    >
    > Originally I sliced the leftside out of Fireworks but
    I'm really trying to
    > learn CSS and I want to do this the "right" way.
    >
    >
    http://www.faceyourspaceorganizing.com/test_index.html
    >
    >

  • JScrollPane will not expand

    I have added a JTree which has a default size of 92 x 72 pixels into a JScrollPane which is then added to a frame. My problem is that my JScrollPane has a Viewport size of 0 x 0, even after I set its minimum size to 150 x 150. I cannot view my JTree in the JScrollPane. I have been trying to figure out this problem for the past two days. This is getting really annoying. My code is below, comments or suggestions appreciated.
    public class GUI_Launch
    public static void main(String[] args)
    SpringLayout layout = new SpringLayout();
    JFrame frame = new JFrame();
    frame.setTitle("GUI Demo");
    frame.setSize(WIDTH, HEIGHT);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.show();
    SimpleTree tree = new SimpleTree(frame, layout);
    private static final int WIDTH = 700;
    private static final int HEIGHT = 700;
    class SimpleTree extends JFrame
    public SimpleTree(JFrame frame, SpringLayout layout)
    DefaultMutableTreeNode top =
    new DefaultMutableTreeNode("The World");
    Container contentPane = frame.getContentPane();
    contentPane.setLayout(layout);
    CreateNodes(top);
    JTree tree = new JTree(top);
    tree.getSelectionModel().setSelectionMode
    (TreeSelectionModel.SINGLE_TREE_SELECTION);
    JScrollPane treeView = new JScrollPane();
    treeView.add(tree);
    treeView.setHorizontalScrollBarPolicy(
    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    treeView.setVerticalScrollBarPolicy(
    ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
    tree.setVisibleRowCount(5);
    JViewport port = treeView.getViewport();
    port.setMinimumSize(new Dimension(150,150));
    treeView.setMinimumSize(new Dimension(150,160));
    contentPane.add(treeView);
    Spring s = Spring.constant(100,300,800);
    layout.putConstraint(SpringLayout.EAST, treeView, s, SpringLayout.EAST, contentPane);
    layout.putConstraint(SpringLayout.WEST, treeView, s, SpringLayout.WEST, contentPane);
    layout.putConstraint(SpringLayout.NORTH, treeView, s, SpringLayout.NORTH, contentPane);
    layout.putConstraint(SpringLayout.SOUTH, treeView, s, SpringLayout.SOUTH, contentPane);
    treeView.revalidate();
    System.out.println(port.getViewSize());
    System.out.println(treeView.getX());
    System.out.println(treeView.getY());
    }

    Camickr,
    I think you are correct about the paint issue. However, after adding a frame.setVisible(true); command as the last statement in my SimpleTree method, the frame still shows up blank. I do not think that my layout manager is laying out the components. Even after issuing frame.setVisible and frame.show, my tree.getSize() still returns dimensions of 0 by 0. My JTree resides within a JScrollPane, but neither show up in the frame. There is 1 component in my frame and 4 inside of my JScrollPane. The JTree is the only component that I placed inside of the JScrollPane, but I suppose that the getComponentCount() method counted 4 by including all the components that make up a JTree. Anyway, if you have any insight as to why nothing shows up in my JFrame and the components are all sized to be 0 x 0, let me know. My code is below.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.JScrollPane.*;
    import java.awt.Dimension.*;
    import javax.swing.border.*;
    import javax.swing.SpringLayout.*;
    import java.lang.Integer.*;
    public class GUI_Launch
    public static void main(String[] args)
        SpringLayout layout = new SpringLayout();
        JFrame frame = new JFrame();
        frame.setTitle("GUI Demo");
        frame.setSize(WIDTH, HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        SimpleTree tree = new SimpleTree(frame, layout);
    private static final int WIDTH = 700;
    private static final int HEIGHT = 700;
    class SimpleTree extends JFrame
        public SimpleTree(JFrame frame, SpringLayout layout)
            DefaultMutableTreeNode top =
                    new DefaultMutableTreeNode("The World");
            Container contentPane = frame.getContentPane();
            contentPane.setLayout(layout);
            CreateNodes(top);
            JTree tree = new JTree(top);
            tree.getSelectionModel().setSelectionMode
                    (TreeSelectionModel.SINGLE_TREE_SELECTION);
            JScrollPane treeView = new JScrollPane();
            treeView.add(tree);
            treeView.setHorizontalScrollBarPolicy(
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            treeView.setVerticalScrollBarPolicy(
            ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
            tree.setVisibleRowCount(5);
            JViewport port = treeView.getViewport();
            port.setMinimumSize(new Dimension(150,150));
            treeView.setMinimumSize(new Dimension(150,160));
            contentPane.add(treeView);
            Spring s = Spring.constant(100,300,500);
            layout.putConstraint(SpringLayout.EAST, treeView, s, SpringLayout.EAST, contentPane);
            layout.putConstraint(SpringLayout.WEST, treeView, s, SpringLayout.WEST, contentPane);
            layout.putConstraint(SpringLayout.NORTH, treeView, s, SpringLayout.NORTH, contentPane);
            layout.putConstraint(SpringLayout.SOUTH, treeView, s, SpringLayout.SOUTH, contentPane);
            frame.setVisible(true);
            frame.show();
            System.out.println(port.getViewSize());
            System.out.println(frame.getComponentCount());
            System.out.println(treeView.getComponentCount());
            System.out.println(tree.getSize());
            System.out.println(treeView.getX());
            System.out.println(treeView.getY());
        private void CreateNodes(DefaultMutableTreeNode top)
            DefaultMutableTreeNode state = null;
            DefaultMutableTreeNode city = null;
            state = new DefaultMutableTreeNode("Oregon");
            city = new DefaultMutableTreeNode("Portland");
            state.add(city);
            city = new DefaultMutableTreeNode("Bend");
            state.add(city);
            city = new DefaultMutableTreeNode("Salem");
            state.add(city);
            top.add(state);
            state = new DefaultMutableTreeNode("Indiana");
            city = new DefaultMutableTreeNode("South Bend");
            state.add(city);
            top.add(state);
            state = new DefaultMutableTreeNode("New York");
            city = new DefaultMutableTreeNode("New York");
            state.add(city);    
            top.add(state);
    }

  • JTextPane inside JScrollPane resizing when updated

    Hiya all,
    I've been struggling with this problem and checking the forums, but didn't find a solution, so I hope someone can help...at least help me for the nice picture :) It has to do with JTextPane's automatically resizing to their content on a GUI update, rather than scrollbars appearing (the desired result).
    Basically, I have a scenario where I am creating a series of multiple choice answers for a question. Each answer consists of a JTextPane inside a JScrollPane, and a JRadioButton, which are all contained in a JPanel (called singleAnswerPanel). So for 2 answers, I would have 2 of these singleAnswerPanels. There is a one large JPanel that contains all the singleAnswerPanels (called allAnswersPanel). This allAnswersPanel is contained in a JScrollPane. Graphically, this looks like:
       |       JPanel (allAnswersPanel) inside a JScrollPane            |
       |                                                                |
       |  ------------------------------------------------------------  |
       | |     JPanel (singleAnswerPanel)                             | |
       | |    ----------------------------------                      | |
       | |   |  JTextPane inside a JScrollPane  |     * JRadioButton  | |
       | |    ----------------------------------                      | |
       | |                                                            | |
       |  ------------------------------------------------------------  |
       |                                                                |
       |                                                                |
       |  ------------------------------------------------------------  |
       | |     JPanel (singleAnswerPanel)                             | |
       | |    ----------------------------------                      | |
       | |   |  JTextPane inside a JScrollPane  |     * JRadioButton  | |
       | |    ----------------------------------                      | |
       | |                                                            | |
       |  ------------------------------------------------------------  |
       |                                                                |
        ----------------------------------------------------------------So above, I show 2 answers that can be filled in with text. So assuming both answer JTextPanes are filled with text beyond their current border (scrollbars appear as expected) and the user wishes to add more answers. I have a button to add another singleAnswerPanel to the containing JPanel (allAnswersPanel), and then I validate the main JScrollPane that contains the allAnswersPanel as it's view. The problem that occurs is the existing single answer JTextPanes resize to the size of their text and the vertical scrollbars (only vertical ones setup) of the JTextPanes dissappear! My intent is to keep the existing JScrollPanes the same size (with their scrollbars) when a new answer is added.
    The code snippet below shows what gets done when a new answer is added:
    private void createAnswer()
        // The panel that will hold the new single answer JTextPane pane
        // (inside a JScrollPane) and radio button.
        JPanel singleAnswerPanel = new JPanel();
        // Create the text pane for the single answer.
        JTextPane singleAnswerTextPane = new JTextPane();
        Dimension dimensions = new Dimension(200, 30);
        singleAnswerTextPane.setPreferredSize(dimensions);
        singleAnswerTextPane.setMaximumSize(dimensions);
        // Create a scroll pane and add the single answer text pane.
        JScrollPane singleAnswerScrollPane =
         new JScrollPane(singleAnswerTextPane);
        // Create a radio button that is associated with the single
        // answer text pane above.
        JRadioButton singleAnswerRadioButton = new JRadioButton();
        // Add the scroll pane and radio button to the panel (for a single
        // answer).
        singleAnswerPanel.add(singleAnswerScrollPane);
        singleAnswerPanel.add(singleAnswerRadioButton);
        // Add the panel holding a single answer to the panel holding
        // all the answers.
        m_allAnswersPanel.add(singleAnswerPanel);
        // Update the display.  m_allAnswersScrollPane is a JScrollPane
        // that has the m_allAnswersPanel (JPanel) as its view.
        m_allAnswersScrollPane.validate();
    }     Sorry for the length of the message, but I really want to solve this problem. So again, when updating the JScrollPane with validate(), the JTextPane for a single answer resizes to it's contents (plain text currently) and loses it's vertical scrollbars, but I want it to stay the same size and maintain the scrollbars.
    Thanks!

    http://java.sun.com/docs/books/tutorial/uiswing/mini/layout.htmlimport javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    public class Test extends JFrame {
        int cnt=0;
        Random r = new Random();
        String[] nouns = {"air","water","men","idjits"};
        JPanel mainPanel = new JPanel(new GridBagLayout());
        JScrollPane mainScroll = new JScrollPane(mainPanel);
        JScrollBar mainScrollBar = mainScroll.getVerticalScrollBar();
        public Test() {
         setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         Container content = getContentPane();
         content.add(new JLabel("QuizMaster 2003"), BorderLayout.NORTH);
         content.add(mainScroll, BorderLayout.CENTER);
         JButton jb = new JButton("New");
         content.add(jb, BorderLayout.SOUTH);
         jb.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent ae) {
              JPanel questionPanel = new JPanel(new GridBagLayout());
              questionPanel.add(new JLabel("Question "+cnt++),
                   new GridBagConstraints(0,0,1,1,0.0,0.0,
                        GridBagConstraints.EAST, GridBagConstraints.NONE,
                        new Insets(1,2,1,2),0,0));
              questionPanel.add(new JLabel("Why is there "+
                            nouns[r.nextInt(nouns.length)]+"?"),
                   new GridBagConstraints(1,0,1,1,0.0,0.0,
                        GridBagConstraints.EAST, GridBagConstraints.NONE,
                        new Insets(1,2,1,2),0,0));
              JTextArea jta = new JTextArea();
              JScrollPane jsp = new JScrollPane(jta);
              jsp.setPreferredSize(new Dimension(300,50));
              questionPanel.add(jsp, new GridBagConstraints(0,1,2,1,0.0,0.0,
                        GridBagConstraints.EAST, GridBagConstraints.BOTH,
                        new Insets(1,2,1,2),0,0));
              mainPanel.add(questionPanel, new GridBagConstraints(0,cnt,1,1,0.0,0.0,
                            GridBagConstraints.EAST,GridBagConstraints.NONE,
                            new Insets(0,0,0,0),0,0));
              mainPanel.revalidate();
              mainScroll.getViewport().setViewPosition(new Point(0, mainPanel.getHeight()));
         setSize(400,300);
         show();
        public static void main( String args[] ) { new Test(); }
    }

  • Getting Visible text - JTextPane in a JScrollPane

    I have a JTextPane wrapped in a JScrollPane. I want to be able to get the text that is visible at any given time. I want JUST the text that is visible, not the entire text of the document.
    The method to use is obviously getText(int offset, int length), which is from JTextComponent.
    I am wondering how I can retrieve the given offset (ie. the position of the very first visible character) and length (ie. the ending position of the last visible character minus the position of the starting character) from either the JScrollPane or the JTextPane.
    I believe that this might be a rather complex problem as I'm qutie certain I am going to have to manually compute a few things by using several different views.
    Any help anyone could offer would be most appreciated.

    Hi camickr
    I got the JScrollPane now thanks.
    Now I'm still confused on how to solve the original problem.
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    public class TestJTextPane extends JTextPane implements ComponentListener{
          public static void main (String args[]){
               JFrame mainFrame = new JFrame();
               mainFrame.setSize(500,300);
               mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               mainFrame.getContentPane().add(new JScrollPane(new TestJTextPane()));
               mainFrame.setVisible(true);
          public TestJTextPane(){
                this.addComponentListener(this);
          private void viewVisibleText(){
               int offSet = 0;
               int length = 0;
               try{
                    JScrollPane scrollPane = (JScrollPane) this.getParent().getParent();
                    System.out.println(scrollPane.getViewport().getVisibleRect());
                    System.out.println(this.viewToModel(scrollPane.getViewport().getVisibleRect().getLocation()));
               catch (Exception e){
                    e.printStackTrace();
         public void componentResized(ComponentEvent arg0) {
              viewVisibleText();
         public void componentMoved(ComponentEvent arg0) {
              viewVisibleText();
         public void componentShown(ComponentEvent arg0) {
         public void componentHidden(ComponentEvent arg0) {
              // TODO Auto-generated method stub
    }If you run this, you will see that the Rectangle for the getVisibleRect() does not changed, and the call to viewToModel will always return 0.
    Can you please point out where I'm going wrong.
    Thanks for the help

  • Getting JScrollPane to resize with container...

    I am tearing my hair out trying to get a JScrollPane containing a JTree to properly resize when its parent container is resized (and indeed to be sized properly when first added to the container).
    Currently, the scrollpane sizes itself to its child (tree), which is much larger than the preferred size of the containing JPanel. consequently no scrollbars are shown, and the tree is centered in the display.
    Any help greatly appreciated!
    A minimal example of code that behaves badly in this respect follows:
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //ScrollTest.java
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import java.awt.event.WindowAdapter;
    public class ScrollTest{
    public static void main(String[] args){
    DefaultMutableTreeNode top = new DefaultMutableTreeNode("TEST");
    DefaultMutableTreeNode curNode = top;
    JTree jt = new JTree(top);
    StringBuffer sb = new StringBuffer("TEST:");
    for (int i=0;i<10;i++){
    DefaultMutableTreeNode n = new DefaultMutableTreeNode(sb.toString());
    curNode.add(n);
    curNode = n;
    sb.append(sb.toString());
    jt.expandRow(i);
    JScrollPane jsp = new JScrollPane(jt);
    JPanel jp = new JPanel();
    jp.setPreferredSize(new Dimension(200,200));
    jp.add(jsp,BorderLayout.CENTER);
    JFrame jf = new JFrame("Test");
    jf.setContentPane(jp);
    jf.addWindowListener(new WindowAdapter(){
    public void windowClosing(){
    System.exit(0);
    jf.pack();
    jf.show();
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    ok: don't set the the content pane.
    add the JPanel to the content pane: getContentPane.add(jp, BorderLayout.CENTER);
    (the content pane of a JFrame has a BorderLayout by default), that way your scroll pane should resize automatically when and if you resize the JFrame.
    thomas

  • How to implement setLineWrap equivalent method in a JTextPane

    I using a JTextPane in a chat Window, but if in this are writing a very large line this don't break lines as in the case of the setLineWrap(true) method for a JTextArea.
    How to implement break lines in a JTextPane equivalent to the setLineWrap(true) method for a JTextArea?

    ???import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test3 extends JFrame {
      public Test3() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        JTextPane jtp = new JTextPane();
        StringBuffer sb = new StringBuffer();
        for (int i=0; i<100; i++) sb.append("this is some text.  ");
        jtp.setText(sb.toString());
        content.add(new JScrollPane(jtp), BorderLayout.CENTER);
        setSize(400, 400);
        setVisible(true);
      public static void main(String[] args) { new Test3(); }
    }

  • More JTextPane Questions

    Hi Guys
    I posted this question on the Java Ranch forums yesterday evening, but I haven't received a response yet, so I figured that I'd try these forums as well. You can view the other thread here; http://www.coderanch.com/t/554155/GUI/java/JTextPane-Questions.
    We're trying to build a simple WYSIWYG HTML editor using a JTextPane. I've used Charles Bell's example, available here; http://www.artima.com/forums/flat.jsp?forum=1&thread=1276 as a reference. My biggest gripe with it at the moment is that bullets aren't working as I would expect them to. If I highlight text and click the "Bullet" button, I want a bullet to be placed immediately before the highlighted text, on the same line. If I try to do this, my code is creating bullets, but it moves the selected text one line down. I've gone through the Oracle tutorial on text components, but I couldn't find anything that helped me with this particular issue.
    Also, if I copy and paste text into my JTextPane, the pasted text always appears on a new line (a new paragraph tag in the actual HTML). Is there a way to prevent the JTextPane from creating new paragraphs?
    Lastly, I'm flabbergasted as to why my buttons actually work. I can't see anything that explicitly links my buttons to my HTMLEditorKit or my JTextPane. Short of a little voodoo man living under my keyboard, how on earth do my buttons/actions know that they should update the JTextPane?
    The code is as follows;
    package myhtmleditor;
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Action;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.SwingUtilities;
    import javax.swing.text.StyledEditorKit;
    import javax.swing.text.html.HTML;
    import javax.swing.text.html.HTMLDocument;
    import javax.swing.text.html.HTMLEditorKit;
    public class Main {
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("My HTML Editor");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setSize(500, 500);
                    frame.setLayout(new BorderLayout());
                    JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
                    HTMLDocument document = new HTMLDocument();
                    final JTextPane htmlEditorPane = new JTextPane(document);
                    Action bold = new StyledEditorKit.BoldAction();
                    Action italic = new StyledEditorKit.ItalicAction();
                    Action underline = new StyledEditorKit.UnderlineAction();
                    JButton boldButton = new JButton(bold);
                    boldButton.setText("Bold");
                    buttonsPanel.add(boldButton);
                    JButton italicButton = new JButton(italic);
                    italicButton.setText("Italic");
                    buttonsPanel.add(italicButton);
                    JButton underlineButton = new JButton(underline);
                    underlineButton.setText("Underline");
                    buttonsPanel.add(underlineButton);
                    HTMLEditorKit.InsertHTMLTextAction bulletAction = new HTMLEditorKit.InsertHTMLTextAction("Bullet", "<ul><li> </li></ul>", HTML.Tag.BODY, HTML.Tag.UL);
                    JButton bulletButton = new JButton(bulletAction);
                    bulletButton.setText("Bullet");
                    buttonsPanel.add(bulletButton);
                    JButton printButton = new JButton("Print to Console");
                    printButton.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                            System.out.println(htmlEditorPane.getText());
                    buttonsPanel.add(printButton);
                    htmlEditorPane.setContentType("text/html");
                    HTMLEditorKit editorKit = new HTMLEditorKit();
                    htmlEditorPane.setEditorKit(editorKit);
                    frame.add(buttonsPanel, BorderLayout.NORTH);
                    frame.add(new JScrollPane(htmlEditorPane), BorderLayout.CENTER);
                    frame.setVisible(true);
    }Thank you for your input.
    Cheers,
    rfnel

    See how the bullet action changes HTML (compare getText() result before and after the bullet applying. It seems you need more smart way of adding bullets.
    Answer some questions if user selects whole paragraph should the <p> tag be removed and replaced with <li>? If user selects just one word in the paragraph and pressed bullet should the whole paragraph be bulleted?
    When you copy something you clipboard contains something like this "<html><body> content</body></html>". Try to override read() method of your kit (or Reader) to skip the main tags.
    For components see ObjectView class source.
    In fact when HTMLDocument is created from String components classes are created and stored in attributes of Elements. Then during rendering ComponentView extension (ObjectView) creates components.

  • From jtextpane to jeditorpane

    I'd like to create a complete text editor so, i made these two code, but the first it's based on jtextpane and the second on a jeditorpane. I want to link toghether the second with the firt code , to have a cpmplete text editor. The problem is that i don't know how to do this. The fisrt think i thought to do was transform the jtext in the fisrt code in a jeditor but jeditor don't recognize the function 'append' .. Could someone help me? Thanks
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package GUI;
    import java.awt.Toolkit;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.StringSelection;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;
    import javax.swing.filechooser.FileNameExtensionFilter;
    * @author Elena
    public class Form extends javax.swing.JFrame {
    String ClipboardData = "";
    private Object CurrentFileDirectory;
    * Creates new form Form
    public Form() {
    initComponents();
    * This method is called from within the constructor to initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is always
    * regenerated by the Form Editor.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jScrollPane2 = new javax.swing.JScrollPane();
    editorpane = new javax.swing.JEditorPane();
    jMenuBar1 = new javax.swing.JMenuBar();
    Open = new javax.swing.JMenu();
    New = new javax.swing.JMenuItem();
    Openfile = new javax.swing.JMenuItem();
    Save = new javax.swing.JMenuItem();
    SaveAs = new javax.swing.JMenuItem();
    Exit = new javax.swing.JMenuItem();
    Cut = new javax.swing.JMenu();
    jMenuItem6 = new javax.swing.JMenuItem();
    Copy = new javax.swing.JMenuItem();
    Paste = new javax.swing.JMenuItem();
    Delete = new javax.swing.JMenuItem();
    SelectAll = new javax.swing.JMenuItem();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Java Text Editor");
    jScrollPane2.setViewportView(editorpane);
    Open.setText("File");
    New.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
    New.setText("New");
    New.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    NewActionPerformed(evt);
    Open.add(New);
    Openfile.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
    Openfile.setText("Open...");
    Openfile.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    OpenfileActionPerformed(evt);
    Open.add(Openfile);
    Save.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
    Save.setText("Save");
    Save.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    SaveActionPerformed(evt);
    Open.add(Save);
    SaveAs.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
    SaveAs.setText("Save As...");
    SaveAs.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    SaveAsActionPerformed(evt);
    Open.add(SaveAs);
    Exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_0, java.awt.event.InputEvent.CTRL_MASK));
    Exit.setText("Exit");
    Exit.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    ExitActionPerformed(evt);
    Open.add(Exit);
    jMenuBar1.add(Open);
    Cut.setText("Edit");
    jMenuItem6.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
    jMenuItem6.setText("Cut");
    jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jMenuItem6ActionPerformed(evt);
    Cut.add(jMenuItem6);
    Copy.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
    Copy.setText("Copy");
    Copy.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    CopyActionPerformed(evt);
    Cut.add(Copy);
    Paste.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
    Paste.setText("Paste");
    Paste.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    PasteActionPerformed(evt);
    Cut.add(Paste);
    Delete.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DELETE, 0));
    Delete.setText("Delete");
    Delete.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    DeleteActionPerformed(evt);
    Cut.add(Delete);
    SelectAll.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
    SelectAll.setText("Select All");
    SelectAll.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    SelectAllActionPerformed(evt);
    Cut.add(SelectAll);
    jMenuBar1.add(Cut);
    setJMenuBar(jMenuBar1);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 479, Short.MAX_VALUE)
    pack();
    }// </editor-fold>
    private void NewActionPerformed(java.awt.event.ActionEvent evt) {                                   
    editorpane.setText("");
    private void ExitActionPerformed(java.awt.event.ActionEvent evt) {                                    
    System.exit(0);
    private void DeleteActionPerformed(java.awt.event.ActionEvent evt) {                                      
    editorpane.replaceSelection("");
    private void SaveAsActionPerformed(java.awt.event.ActionEvent evt) {                                      
    JFileChooser sdChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("DOCX File", "txt");
    sdChooser.setFileFilter(filter);
    int returnVal = sdChooser.showSaveDialog(null);
    try{
    if(returnVal == JFileChooser.APPROVE_OPTION){
    File directory = sdChooser.getCurrentDirectory();
    String path = directory.getAbsolutePath();
    String fileName = sdChooser.getSelectedFile().getName();
    if(fileName.contains(".docx")){
    }else{
    fileName = fileName + ".docx";
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path + "\\" + fileName)));
    bw.write(editorpane.getText());
    bw.close();
    } catch(IOException e){
    JOptionPane.showMessageDialog(null, "ERROR!");
    private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {                                          
    ClipboardData = editorpane.getSelectedText();
    StringSelection stringSelection = new StringSelection(ClipboardData);
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(stringSelection, null);
    editorpane.replaceSelection("");
    private void CopyActionPerformed(java.awt.event.ActionEvent evt) {                                    
    ClipboardData = editorpane.getSelectedText();
    StringSelection stringSelection = new StringSelection(ClipboardData);
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(stringSelection, null);
    private void PasteActionPerformed(java.awt.event.ActionEvent evt) {                                     
    editorpane.append(ClipboardData);
    private void SelectAllActionPerformed(java.awt.event.ActionEvent evt) {                                         
    editorpane.selectAll();
    private void OpenfileActionPerformed(java.awt.event.ActionEvent evt) {                                        
    JFileChooser opChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("DOCX file", "docx");
    opChooser.setFileFilter(filter);
    int returnval = opChooser.showOpenDialog(null);
    File chosenFile = opChooser.getSelectedFile();
    try {
    if(returnval == JFileChooser.APPROVE_OPTION){
    BufferedReader br = new BufferedReader(new FileReader(chosenFile));
    editorpane.setText("");
    String data;
    while((data = br.readLine()) != null) {
    editorpane.append(data + "\n");}
    br.close();
    }catch(IOException e){
    JOptionPane.showMessageDialog(null, "ERROR!" );
    private void SaveActionPerformed(java.awt.event.ActionEvent evt) {                                    
    if("".equals(CurrentFileDirectory)){
    JFileChooser sdChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("DOCX file", "docx");
    sdChooser.setFileFilter(filter);
    int returnval = sdChooser.showOpenDialog(null);
    try{
    if(returnval == JFileChooser.APPROVE_OPTION){
    File directory = sdChooser.getCurrentDirectory();
    String path = directory.getAbsolutePath();
    String fileName = sdChooser.getSelectedFile().getName();
    if(fileName.contains(".docx")){
    }else{
    fileName = fileName + ".docx";
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path + "\\" + fileName)));
    bw.write(editorpane.getText());
    bw.close();}
    }catch(IOException e){     
    JOptionPane.showMessageDialog(null, "ERROR!");
    * @param args the command line arguments
    public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
    * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
    try {
    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
    if ("Nimbus".equals(info.getName())) {
    javax.swing.UIManager.setLookAndFeel(info.getClassName());
    break;
    } catch (ClassNotFoundException ex) {
    java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
    java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
    java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
    java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    //</editor-fold>
    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
    new Form().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JMenuItem Copy;
    private javax.swing.JMenu Cut;
    private javax.swing.JMenuItem Delete;
    private javax.swing.JMenuItem Exit;
    private javax.swing.JMenuItem New;
    private javax.swing.JMenu Open;
    private javax.swing.JMenuItem Openfile;
    private javax.swing.JMenuItem Paste;
    private javax.swing.JMenuItem Save;
    private javax.swing.JMenuItem SaveAs;
    private javax.swing.JMenuItem SelectAll;
    private javax.swing.JEditorPane editorpane;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem6;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.GraphicsEnvironment;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Action;
    import javax.swing.JButton;
    import javax.swing.JColorChooser;
    import javax.swing.JComboBox;
    import javax.swing.JDialog;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.Element;
    import javax.swing.text.MutableAttributeSet;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyledDocument;
    import javax.swing.text.StyledEditorKit;
    public class Colore {
    public Colore() {
    JFrame frame = new JFrame();
    JTextPane textPane = new JTextPane();
    JScrollPane scrollPane = new JScrollPane(textPane);
    JPanel north = new JPanel();
    JMenuBar menu = new JMenuBar();
    JMenu styleMenu = new JMenu();
    styleMenu.setText("Style");
    Action boldAction = new BoldAction();
    boldAction.putValue(Action.NAME, "Bold");
    styleMenu.add(boldAction);
    Action italicAction = new ItalicAction();
    italicAction.putValue(Action.NAME, "Italic");
    styleMenu.add(italicAction);
    Action foregroundAction = new ForegroundAction();
    foregroundAction.putValue(Action.NAME, "Color");
    styleMenu.add(foregroundAction);
    Action formatTextAction = new FontAndSizeAction();
    formatTextAction.putValue(Action.NAME, "Font and Size");
    styleMenu.add(formatTextAction);
    menu.add(styleMenu);
    north.add(menu);
    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(north, BorderLayout.NORTH);
    frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
    frame.setSize(800, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    public static void main(String[] args) {
    new Culo();
    class BoldAction extends StyledEditorKit.StyledTextAction {
    private static final long serialVersionUID = 9174670038684056758L;
    public BoldAction() {
    super("font-bold");
    public String toString() {
    return "Bold";
    public void actionPerformed(ActionEvent e) {
    JEditorPane editor = getEditor(e);
    if (editor != null) {
    StyledEditorKit kit = getStyledEditorKit(editor);
    MutableAttributeSet attr = kit.getInputAttributes();
    boolean bold = (StyleConstants.isBold(attr)) ? false : true;
    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setBold(sas, bold);
    setCharacterAttributes(editor, sas, false);
    class ItalicAction extends StyledEditorKit.StyledTextAction {
    private static final long serialVersionUID = -1428340091100055456L;
    public ItalicAction() {
    super("font-italic");
    public String toString() {
    return "Italic";
    public void actionPerformed(ActionEvent e) {
    JEditorPane editor = getEditor(e);
    if (editor != null) {
    StyledEditorKit kit = getStyledEditorKit(editor);
    MutableAttributeSet attr = kit.getInputAttributes();
    boolean italic = (StyleConstants.isItalic(attr)) ? false : true;
    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setItalic(sas, italic);
    setCharacterAttributes(editor, sas, false);
    class ForegroundAction extends StyledEditorKit.StyledTextAction {
    private static final long serialVersionUID = 6384632651737400352L;
    JColorChooser colorChooser = new JColorChooser();
    JDialog dialog = new JDialog();
    boolean noChange = false;
    boolean cancelled = false;
    public ForegroundAction() {
    super("foreground");
    public void actionPerformed(ActionEvent e) {
    JTextPane editor = (JTextPane) getEditor(e);
    if (editor == null) {
    JOptionPane.showMessageDialog(null,
    "You need to select the editor pane before you can change the color.", "Error",
    JOptionPane.ERROR_MESSAGE);
    return;
    int p0 = editor.getSelectionStart();
    StyledDocument doc = getStyledDocument(editor);
    Element paragraph = doc.getCharacterElement(p0);
    AttributeSet as = paragraph.getAttributes();
    fg = StyleConstants.getForeground(as);
    if (fg == null) {
    fg = Color.BLACK;
    colorChooser.setColor(fg);
    JButton accept = new JButton("OK");
    accept.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    fg = colorChooser.getColor();
    dialog.dispose();
    JButton cancel = new JButton("Cancel");
    cancel.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    cancelled = true;
    dialog.dispose();
    JButton none = new JButton("None");
    none.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    noChange = true;
    dialog.dispose();
    JPanel buttons = new JPanel();
    buttons.add(accept);
    buttons.add(none);
    buttons.add(cancel);
    dialog.getContentPane().setLayout(new BorderLayout());
    dialog.getContentPane().add(colorChooser, BorderLayout.CENTER);
    dialog.getContentPane().add(buttons, BorderLayout.SOUTH);
    dialog.setModal(true);
    dialog.pack();
    dialog.setVisible(true);
    if (!cancelled) {
    MutableAttributeSet attr = null;
    if (editor != null) {
    if (fg != null && !noChange) {
    attr = new SimpleAttributeSet();
    StyleConstants.setForeground(attr, fg);
    setCharacterAttributes(editor, attr, false);
    }// end if color != null
    noChange = false;
    cancelled = false;
    private Color fg;
    class FontAndSizeAction extends StyledEditorKit.StyledTextAction {
    private static final long serialVersionUID = 584531387732416339L;
    private String family;
    private float fontSize;
    JDialog formatText;
    private boolean accept = false;
    JComboBox fontFamilyChooser;
    JComboBox fontSizeChooser;
    public FontAndSizeAction() {
    super("Font and Size");
    public String toString() {
    return "Font and Size";
    public void actionPerformed(ActionEvent e) {
    JTextPane editor = (JTextPane) getEditor(e);
    int p0 = editor.getSelectionStart();
    StyledDocument doc = getStyledDocument(editor);
    Element paragraph = doc.getCharacterElement(p0);
    AttributeSet as = paragraph.getAttributes();
    family = StyleConstants.getFontFamily(as);
    fontSize = StyleConstants.getFontSize(as);
    formatText = new JDialog(new JFrame(), "Font and Size", true);
    formatText.getContentPane().setLayout(new BorderLayout());
    JPanel choosers = new JPanel();
    choosers.setLayout(new GridLayout(2, 1));
    JPanel fontFamilyPanel = new JPanel();
    fontFamilyPanel.add(new JLabel("Font"));
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String[] fontNames = ge.getAvailableFontFamilyNames();
    fontFamilyChooser = new JComboBox();
    for (int i = 0; i < fontNames.length; i++) {
    fontFamilyChooser.addItem(fontNames);
    fontFamilyChooser.setSelectedItem(family);
    fontFamilyPanel.add(fontFamilyChooser);
    choosers.add(fontFamilyPanel);
    JPanel fontSizePanel = new JPanel();
    fontSizePanel.add(new JLabel("Size"));
    fontSizeChooser = new JComboBox();
    fontSizeChooser.setEditable(true);
    fontSizeChooser.addItem(new Float(4));
    fontSizeChooser.addItem(new Float(8));
    fontSizeChooser.addItem(new Float(12));
    fontSizeChooser.addItem(new Float(16));
    fontSizeChooser.addItem(new Float(20));
    fontSizeChooser.addItem(new Float(24));
    fontSizeChooser.setSelectedItem(new Float(fontSize));
    fontSizePanel.add(fontSizeChooser);
    choosers.add(fontSizePanel);
    JButton ok = new JButton("OK");
    ok.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    accept = true;
    formatText.dispose();
    family = (String) fontFamilyChooser.getSelectedItem();
    fontSize = Float.parseFloat(fontSizeChooser.getSelectedItem().toString());
    JButton cancel = new JButton("Cancel");
    cancel.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    formatText.dispose();
    JPanel buttons = new JPanel();
    buttons.add(ok);
    buttons.add(cancel);
    formatText.getContentPane().add(choosers, BorderLayout.CENTER);
    formatText.getContentPane().add(buttons, BorderLayout.SOUTH);
    formatText.pack();
    formatText.setVisible(true);
    MutableAttributeSet attr = null;
    if (editor != null && accept) {
    attr = new SimpleAttributeSet();
    StyleConstants.setFontFamily(attr, family);
    StyleConstants.setFontSize(attr, (int) fontSize);
    setCharacterAttributes(editor, attr, false);

    Sorry. My problem is that I want to insert HTML inside the body tag of an HTML page, and I don't know any simple method to get a reference to the <body> element from the JEditorPane widget, I get a reference to the actual HTML document but I can't get a reference of a tag from HTMLDocument either. Thanks.
    Juanjo

  • JTextPane first line read only

    Hi all!
    I'm a beginner in java programming, that said im trying to make a simple text editor (who isn't?), it will be a part of another larger application, nevertheless this editor is a main component, just need some simple editing tips.
    I want to use a JTextPane for the editable surface, this is working fairly well but i am not able access other lines in the editor except from the first one. Meaning that when containing a large piece of text, my JTextPane is only able to edit the first line: For instance the caret will only show it self on the first line, I can write new letters, but only on the first line and i can erase them and so on. What am I missing? Have checked around many places for solutions
    To sum it up; I want to edit every line in my JTextPane instead of just the first one :)

    Ok! thanks a lot for the good advice, ant help is most appreciated. :-)
    Here is a piece of code that demonstrates my problem. Hope it brings insight! Try to write a line of text, then press enter to go to the next line, most probably you will find yourself unable to edit this line.
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.SwingUtilities;
    public class Test implements Runnable
         public static void main(String[] args)
              SwingUtilities.invokeLater(new Test());
         public void run()
              JPanel cP = new JPanel();
              JTextPane tP = new JTextPane();
    JScrollPane sP = new JScrollPane( tP );
    tP.setPreferredSize(new Dimension( 400 , 400 ) );
              sP.setPreferredSize(new Dimension( 300 , 300 ) );
              tP.setEditable(true);
              cP.add(sP);
              JFrame f = new JFrame();
              f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              f.setContentPane( cP );
              f.setLocationRelativeTo( null );
              f.setVisible( true );
    }

  • Insert String to JTextPane as hyperlink

    Hi,
    I have a JTabbedPane with 2 tabs, on each tab is one panel.
    On first pannel I add JTextPane and I would like to insert in this JTextPane some hyperlinks.
    I found some examples in forum, but doesn't work for me.
    Could somebody help me ?
    Thank's.
    Here is my code :
    JTextPane textPane = new JTextPane();
    textPane.setPreferredSize(new Dimension(500,300));
    HTMLEditorKit m_kit = new HTMLEditorKit();
    textPane.setEditorKit(m_kit);
    StyledDocument m_doc = textPane.getStyledDocument();
    textPane.setEditable(false); // only then hyperlinks will work
    panel1.add( textPane,BorderLayout.CENTER); //add textPane to panel of
    //JTabbedPane
    String s = new String("http://google.com");
    SimpleAttributeSet attr2 = new SimpleAttributeSet();
    attr2.addAttribute(StyleConstants.NameAttribute, HTML.Tag.A);
    attr2.addAttribute(HTML.Attribute.HREF, s);
    try{
    m_doc.insertString(m_doc.getLength(), s, attr2);
    }catch(Exception excp){};
    The String s is displayed like text not like hyperlink..

    Hi , You can take a look at this code , this code inserts a string into a StyledDocument in a JTextPane as a hyperlink and on clicking fires the URL on the browser.
    /* Demonstrating creation of a hyperlink inside a StyledDocument in a JTextPane */
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.Border;
    import javax.swing.text.*;
    public class Hyperlink extends JFrame {
        private Container container = getContentPane();
        private int toolXPosition;
        private int toolYPosition;
        private JPanel headingPanel = new JPanel();
        private JPanel closingPanel = new JPanel();
        private final static String LINK_ATTRIBUTE = "linkact";
        private JTextPane textPane;
        private StyledDocument doc;
        Hyperlink() {
              try {
                   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
                   setSize(300, 200);
                   Rectangle containerDimension = getBounds();
                   toolXPosition = (screenDimension.width - containerDimension.width) / 10;
                            toolYPosition = (screenDimension.height - containerDimension.height) / 15;
                            setTitle("HYPERLINK TESTER");
                         setLocation(toolXPosition, toolYPosition);
                         container.add(BorderLayout.NORTH, headingPanel);
                         container.add(BorderLayout.SOUTH, closingPanel);
                   JScrollPane scrollableTextPane;
                   textPane = new JTextPane();
                   //for detecting clicks
                   textPane.addMouseListener(new TextClickListener());
                   //for detecting motion
                   textPane.addMouseMotionListener(new TextMotionListener());
                   textPane.setEditable(false);
                   scrollableTextPane = new JScrollPane(textPane);
                   container.add(BorderLayout.CENTER, scrollableTextPane);
                   container.setVisible(true);
                   textPane.setText("");
                   doc = textPane.getStyledDocument();
                   Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
                   String url = "http://www.google.com";
                   //create the style for the hyperlink
                   Style regularBlue = doc.addStyle("regularBlue", def);
                   StyleConstants.setForeground(regularBlue, Color.BLUE);
                   StyleConstants.setUnderline(regularBlue,true);
                   regularBlue.addAttribute(LINK_ATTRIBUTE,new URLLinkAction(url));
                   Style bold = doc.addStyle("bold", def);
                   StyleConstants.setBold(bold, true);
                   StyleConstants.setForeground(bold, Color.GRAY);
                   doc.insertString(doc.getLength(), "\nStarting HyperLink Creation in a document\n\n", bold);
                   doc.insertString(doc.getLength(), "\n",bold);
                   doc.insertString(doc.getLength(),url,regularBlue);
                   doc.insertString(doc.getLength(), "\n\n\n", bold);
                   textPane.setCaretPosition(0);
              catch (Exception e) {
         public static void main(String[] args) {
              Hyperlink hp = new Hyperlink();
              hp.setVisible(true);
         private class TextClickListener extends MouseAdapter {
                 public void mouseClicked( MouseEvent e ) {
                  try{
                      Element elem = doc.getCharacterElement(textPane.viewToModel(e.getPoint()));
                       AttributeSet as = elem.getAttributes();
                       URLLinkAction fla = (URLLinkAction)as.getAttribute(LINK_ATTRIBUTE);
                      if(fla != null)
                           fla.execute();
                  catch(Exception x) {
                       x.printStackTrace();
         private class TextMotionListener extends MouseInputAdapter {
              public void mouseMoved(MouseEvent e) {
                   Element elem = doc.getCharacterElement( textPane.viewToModel(e.getPoint()));
                   AttributeSet as = elem.getAttributes();
                   if(StyleConstants.isUnderline(as))
                        textPane.setCursor(new Cursor(Cursor.HAND_CURSOR));
                   else
                        textPane.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
         private class URLLinkAction extends AbstractAction{
              private String url;
              URLLinkAction(String bac)
                   url=bac;
                 protected void execute() {
                          try {
                               String osName = System.getProperty("os.name").toLowerCase();
                              Runtime rt = Runtime.getRuntime();
                        if (osName.indexOf( "win" ) >= 0) {
                                   rt.exec( "rundll32 url.dll,FileProtocolHandler " + url);
                                    else if (osName.indexOf("mac") >= 0) {
                                      rt.exec( "open " + url);
                              else if (osName.indexOf("ix") >=0 || osName.indexOf("ux") >=0 || osName.indexOf("sun") >=0) {
                                   String[] browsers = {"epiphany", "firefox", "mozilla", "konqueror",
                                     "netscape","opera","links","lynx"};
                                   // Build a command string which looks like "browser1 "url" || browser2 "url" ||..."
                                   StringBuffer cmd = new StringBuffer();
                                   for (int i = 0 ; i < browsers.length ; i++)
                                        cmd.append((i == 0  ? "" : " || " ) + browsers[i] +" \"" + url + "\" ");
                                   rt.exec(new String[] { "sh", "-c", cmd.toString() });
                   catch (Exception ex)
                        ex.printStackTrace();
                 public void actionPerformed(ActionEvent e){
                         execute();
    }Here , what I have done is associated a mouseListener and a mouseMotionListener with the JTextPane and I have created the hyperlink look with a Style of blue color and underline and have added the LINK_ATTRIBUTE to that Style which takes care of listening to mouse clicks and mouse motion.
    The browser can be started in windows using the default FileProtocolHandler using rundll32 and in Unix/Sun we have to take a wild guess at which browser could be installed , the first browser encountered is started , in Mac open command takes care of starting the browser.
    Hope this is useful.

  • JTextPane AutoScroll

    Hello everyone
    I have a JPanel that I used as a container to stack JTextPane components and a JScrollPane to control the viewport. Whenever a new JTextPane is added (or its content modified), the JScrollPane scrolls automatically to show it. How can I avoid this? I don't want the JScrollPane to scroll automatically to anywhere unless the user does that manually.
    Many thanks

    if (model.getValue() == model.getMaximum() - model.getExtent()) The values are never equal and are out by 3 pixels with just happens to be the textPane.getInsets().bottom value.
    The following works:
    textPane.setMargin( new Insets(3, 3, 0, 3) );The following doesn't work and the difference is out by 7:
    textPane.setMargin( new Insets(3, 3, 7, 3) );The code works on a JTextArea because the insets are 0.

  • Reinitializing JScrollPane's viewport

    I display a JDialog which contains a JScrollPane which shows a JTextPane in it's viewport.
    Once the user is done with the JDialog, I hide it from view and the next time that the user wants it
    I want to scoll the vertical scollbar so that it displays the beginning of the JTextPane again instead of where the user left it previously. How can I do this?
    Any help is much appreciated.

    textPane.setCaretPosition(0);For some reason, it isn't working. That was actualy the first thing that came to mind and which I attempted.
    Here is the code snippet:
    public class Cont extends javax.swing.JDialog {
            protected javax.swing.JTabbedPane tabbedpane;    
            protected SoAndSo one = new SoAndSo();
            protected SuchAndSuch two = new SuchAndSuch();
            public Cont(){
                init();
                setTitle("Cont");           
                setModal(true);
            public void init(){                       
                tabbedpane = new javax.swing.JTabbedPane();
                tabbedpane.add("SoAndSo",one);
                tabbedpane.add("SuchAndSuch", two);           
                java.awt.Container container = getContentPane();
                container.add(tabbedpane,java.awt.BorderLayout.CENTER);
                setBounds(200,120,600,400);
                setResizable(false);
                tabbedpane.addChangeListener(new javax.swing.event.ChangeListener(){
                    public void stateChanged(javax.swing.event.ChangeEvent e){
                        if(tabbedpane.getSelectedIndex()==0){
                            one.initialize();
                        else if(tabbedpane.getSelectedIndex()==1){
                            two.initialize();
            public class SoAndSo extends javax.swing.JPanel{           
                String content = "   ...";                            
                javax.swing.JScrollPane scrollpane = null;
                javax.swing.JTextPane textpane = null;
                public SoAndSo(){
                    init();
                    setSize(590,390);               
                public void init(){
                    scrollpane = new javax.swing.JScrollPane();               
                    scrollpane.setPreferredSize(new java.awt.Dimension(590,300));               
                    textpane = new javax.swing.JTextPane();
                    textpane.setEditable(false);
                    scrollpane.setViewportView(textpane);
                    add(java.awt.BorderLayout.CENTER, scrollpane);               
                    textpane.setText(content);               
                    textpane.setFont(new java.awt.Font("SanSerif",java.awt.Font.BOLD,11));
                public void initialize(){
                    textpane.setCaretPosition(0);
            public class SuchAndSuch extends javax.swing.JPanel{           
                String content = "  ....";
                protected javax.swing.JTextPane textpane = null;
                public SuchAndSuch(){
                    init();
                    setSize(590,390);               
                public void init(){
                    javax.swing.JScrollPane scrollpane = new javax.swing.JScrollPane();
                    scrollpane.setPreferredSize(new java.awt.Dimension(590,300));               
                    textpane = new javax.swing.JTextPane();
                    textpane.setFont(Main.this.getAvailableFonts());
                    textpane.setEditable(false);
                    scrollpane.setViewportView(textpane);
                    add(java.awt.BorderLayout.CENTER, scrollpane);                                             
                    textpane.setText(content);
                public void initialize(){
                    textpane.setCaretPosition(0);
        }This doesn't behave in the way that I want it to. I didn't matter whether the JTextPane was set to be editable or not, it didn't work either way.

Maybe you are looking for

  • "212 - Rejeicao: Data de emissao NF-e posterior a data de recebimento"

    Bom dia, Estou com o seguinte cenário. Usuário está tentando emitir nota e está ocorrendo o erro "212 - Rejeição: Data de emissão NF-e posterior a data de recebimento". Usuário está em Porto Velho - Rondônia que é uma hora a menos em relação a Brasíl

  • How can I display only one value of a field with two or more values?

    Post Author: skiabox CA Forum: Crystal Reports I have a field in my report with 2 or more values (depending of another field id).For example for id = 1 the report gives me 2 names in that field.For id = 3 the report gives me 3 names in that field.I w

  • Can we extend more than one Listener in a class

    Hii Javaites I am having a class, where i want to implement actionListener,and also ListSelectionListener. public class MyClass implements ActionListener,ListSelectionListener { I have implemented actionPerformed method for actionListener(). But it i

  • Need to be able to move cursor from one computer to another....

    using my mouse. I bought a new MacBook, but still use my old iBook G4 and it works great too. I just can't figure out how to have the cursor go from one to another. I tried Synergy, but it became confusing when I tried to install and have now given u

  • Nokia N8, RM-596 Symbian^3 Keyboard and Font - Lan...

    Back in the 'old' days of Nokia Symbian S60 Devices. Nokia has decided that each phone sold to each region (Europe, China, North America, Middle East Africa, India, Thailand) would have separate language packs. If you live in North America, you proba