Search code examples
javaswingtextjtextpanejeditorpane

How to create formatted text to show in a Java Swing Component (JTextPane, JEditorPane...)


I've searched and researched in everywhere I could to find an answer with no result. So I ask for help once more.

I want to show formatted text in a desktop java swing application. This text would be programactly generated in base of some variable objects and wouldn't be editable.

I don't know if is best to use JTextPane, or JEditorPane, or what. The matter is that I don't find anywhere some manual or tutorial that explain how to use them. Do I have to create an HTMLDocument to insert the text? How do I create it?...

Is is the right way to show text in this case?, or may I go using tables or labels or something like that.

I need some advice from you please, if there is some where I could learn how to do it, tell me please.


Solution

  • Here have a look at this code example, if you want to modify this a bit more, add Font too as an argument and use that appropriate argument at the specified location. Write something in the JTextField and press ENTER several times.

    import java.awt.*;    
    import java.awt.event.*;    
    import javax.swing.*;    
    import javax.swing.border.*;    
    import javax.swing.text.AttributeSet;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyleContext;
    
    public class TextPaneTest extends JFrame {
    
        private JPanel topPanel;
        private JTextPane tPane;
        private JTextField tfield;
        private int counter;
        private Color[] colours = {
                                    Color.RED,
                                    Color.BLUE,
                                    Color.DARK_GRAY,
                                    Color.PINK,
                                    Color.BLACK,
                                    Color.MAGENTA,
                                    Color.YELLOW,
                                    Color.ORANGE
                                  };
    
        public TextPaneTest() {
            counter = 0;   
        }
    
        private void createAndDisplayGUI() {    
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         
    
            EmptyBorder eb = new EmptyBorder(new Insets(10, 10, 10, 10));
    
            tPane = new JTextPane();                
            tPane.setBorder(eb);
            tPane.setMargin(new Insets(5, 5, 5, 5));
            JScrollPane scroller = new JScrollPane();
            scroller.setViewportView(tPane);
    
            tfield = new JTextField();
            tfield.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    counter++;
                    if (counter == 8)
                        counter = 0;
                    String text = tfield.getText() + "\n";
                    appendToPane(tPane, text, colours[counter]);    
                    tfield.selectAll();
                }
            });     
    
            getContentPane().add(scroller, BorderLayout.CENTER);
            getContentPane().add(tfield, BorderLayout.PAGE_END);
    
            setSize(200, 100);
            setVisible(true);
            tfield.requestFocusInWindow();
        }
    
        private void appendToPane(JTextPane tp, String msg, Color c) {
            StyleContext sc = StyleContext.getDefaultStyleContext();
            AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
    
            aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
            aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);
    
            int len = tp.getDocument().getLength();
            tp.setCaretPosition(len);
            tp.setCharacterAttributes(aset, false);
            tp.replaceSelection(msg);
        }
    
        public static void main(String... args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new TextPaneTest().createAndDisplayGUI();
                }
            });
        }
    }