Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styling text in a JTextArea or JTextPane

Basically, I have a JTextPane to hold some text which I wish to style. JTextArea would have been better for me to use but I'm told you cannot style the text in these?

However, the JTextPane doesn't seem to style properly. For example, the following code is just returned with the HTML included:

public static void main(String[] args) {
    JFrame j = new JFrame("Hello!");
    j.setSize(200,200);
    JTextPane k = new JTextPane();
    k.setText("<html><strong>Hey!</strong></html>");
    j.add(k);
    j.setVisible(true);
}

I want to be able to just style some text in a JTextPane when a user interacts with the interface, but so far, it just returns the string with the HTML still in! Help!

like image 965
mino Avatar asked Feb 04 '12 14:02

mino


People also ask

What is the difference between JTextPane and JTextArea?

JTextComponent, with JTextPane coming as a subclass of JEditorPane. From this, it is safe to conclude that JTextPane is a specialized form of JEditorPane which comes with some extra functionality. JTextArea comes with specific functions; one of these prevents it from wrapping text whenever the text is put in.

What is JTextArea used for?

A JTextArea is a multi-line area that displays plain text. It is intended to be a lightweight component that provides source compatibility with the java. awt. TextArea class where it can reasonably do so.

Can you use basic editing operations when entering text in JTextField or JTextArea?

By default, JTextField and JTextArea are editable; you can type and edit in both text components. They can be changed to output-only areas by calling setEditable(false) .

What is JTextPane?

A JTextPane is a subclass of JEditorPane. A JTextPane is used for a styled document with embedded images and components. A JTextPane is a text component that can be marked up with the attributes that are represented graphically and it can use a DefaultStyledDocument as the default model.


1 Answers

If you want to diplaying Html contents in the JTextPane then you have to set for JTextPane#setContentType("text/html");, example here

EDIT:

for JEditorPanes / JTextPanes is there another way by implements StyledDocument, MutableAttributeSet and with customized Highlighter, example here

a.m. way is without using Html syntax

like image 116
mKorbel Avatar answered Oct 02 '22 07:10

mKorbel