Is it possible to set length of paragraph in JTextPane StyledDocument?

491 views Asked by At

I am using JTextPane with StyledDocument, is it possible to set length of its paragraph? My goal is when the length of text which is inserted in the JTextPane is longer than 400px, exceed go to new line.

Edit:

I use method below to set style for textPane

public Style getstyle(String message){
    Style style = context.addStyle("mystyle", null);
    StyleConstants.setForeground(style, Color.GRAY);
    StyleConstants.setBackground(style, new Color(162, 234, 167));
    SimpleAttributeSet mystyle = new SimpleAttributeSet();
    StyleConstants.setFontFamily(style, "SansSerif");
    document.setParagraphAttributes(document.getLength(), message.length(), mystyle, false);
    return style;
}

and use following to insert text to my JTextPane:

try {
    document.insertString(document.getLength(), " "+message+"\n", getStyle(message));
} catch (BadLocationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

I want to set length of paragraph.

Edit2:

I use different style, for different type of my text.

Edit3:

I add my JTextPane to JPanel with scrollbar.

context = new StyleContext();
document = new DefaultStyledDocument(context);
Pane = new JTextPane(document);
Pane.setEditable(false);

Panel.setLayout(new BoxLayout(Panel, BoxLayout.PAGE_AXIS));

JScrollPane scroll = new JScrollPane(Pane);
Panel.add(scroll , BorderLayout.CENTER);
1

There are 1 answers

7
Sergiy Medvynskyy On

Try this:

public static void main(String[] args) throws Exception {
    final JTextPane pane = new JTextPane();
    pane.setContentType("text/html");
    final JFrame frm = new JFrame("Text editor");
    pane.setText("<html><table><tr><td width=\"400\"></td></tr></table</html>");
    frm.add(new JScrollPane(pane));
    frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frm.setSize(500, 500);
    frm.setVisible(true);
}

Your text will go to new line after 400px