Toggle text flow in JTextpane

How do I switch to text wrapping on JTextpane?

public JFrame mainjFrame = new JFrame("Text Editor");
    public JTextPane mainJTextPane = new JTextPane();
        public JScrollPane mainJScrollPane = new JScrollPane(mainJTextPane);
        mainjFrame.add(mainJScrollPane);
+2
source share
2 answers

See No streamlined text panel .

Edit:

Well, if you want to switch behavior, you will also need to switch the value of getScrollableTracksViewportWidth (). See Scroll Bar . You should be able to switch between FIT and STRETCH.

+10
source
package test;

import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;

public class TestVisual extends JFrame {

    private boolean wrapped;
    private JButton toggleButton = null;
    private JTextPane textPane = null;
    private JPanel noWrapPanel = null;
    private JScrollPane scrollPane = null;

    public TestVisual() {
        super();
        init();
    }

    public void init() {
        this.setSize(300, 200);
        this.setLayout(new BorderLayout());

        wrapped = false;

        textPane = new JTextPane();
        noWrapPanel = new JPanel( new BorderLayout() );
        noWrapPanel.add( textPane );

        scrollPane = new JScrollPane( noWrapPanel );

        toggleButton = new JButton("wrap");
        toggleButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                if (wrapped == true){
                    scrollPane.setViewportView(noWrapPanel);
                    noWrapPanel.add(textPane);
                    toggleButton.setText("wrap");
                    wrapped = false;
                }else {
                    scrollPane.setViewportView(textPane);
                    toggleButton.setText("unWrap");
                    wrapped = true;
                }
            }
        });

        this.add(scrollPane, BorderLayout.CENTER);
        this.add(toggleButton, BorderLayout.NORTH);
    }
}


I do not know any other way to what you are looking for.

But it works well.


(Based on camickr .. +1 answer)

+9
source

All Articles