Ferb
Ferb

Reputation: 114

How to enable space-based line-wrapping in JTextPane?

Is it possible to enable space-based line-wrapping in a JTextPane?

Using a JTextArea is not an option because I need to style the content.

Upvotes: 0

Views: 99

Answers (2)

Sharcoux
Sharcoux

Reputation: 6085

This is how you make a default JFrame with a JTextPane and line-wrap. As said by camickr, this is the default behaviour.

package test;

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
/**
 *
 * @author floz
 */
public class Test {

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                final JFrame mainFrame = new JFrame("test");
                mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                final JTextPane field = new JTextPane();
                field.setText("qds qljsd qsld qlskd qlkds fqlk sdkf qlskdfqlk sdlf qsld ql sdf qlskd fqks lqksjd f");

                mainFrame.getContentPane().setLayout(new BorderLayout());
                mainFrame.getContentPane().add(field,BorderLayout.CENTER);
                mainFrame.setSize(200,200);
                mainFrame.setVisible(true);
            }
        });
    }
}

Upvotes: 1

Andreas Brunnet
Andreas Brunnet

Reputation: 732

You could add a listener to the JTextPane document that does the line wrapping like follows:

    pane.getDocument().addDocumentListener(new DocumentListener()
    {

          @Override
          public void insertUpdate(DocumentEvent e) 
          {
               if(e.getOffset() >= pane.getSize().getWidth() / pane.getFont().getSize())
               {
                     String str = pane.getText();
                     if(str.length() <= str.lastIndexOf(32))
                     {
                           try 
                           {
                                e.getDocument().insertString(str.lastIndexOf(32), "\n", pane.getCharacterAttributes());

                           } catch (BadLocationException e1) 
                           {
                                e1.printStackTrace();
                           }
                     }
               }                
          }

          @Override
          public void removeUpdate(DocumentEvent e) {}

          @Override
          public void changedUpdate(DocumentEvent e) {}

   });

Upvotes: 0

Related Questions