3

How would I go about toggling text wrap on a JTextpane?

public JFrame mainjFrame = new JFrame("Text Editor");
    public JTextPane mainJTextPane = new JTextPane();
        public JScrollPane mainJScrollPane = new JScrollPane(mainJTextPane);
        mainjFrame.add(mainJScrollPane);
mKorbel
  • 109,525
  • 20
  • 134
  • 319
GlassGhost
  • 16,906
  • 5
  • 32
  • 45

2 Answers2

11

See No Wrap Text Pane.

Edit:

Well, if you want to toggle the behaviour, then you would also need to toggle the getScrollableTracksViewportWidth() value. See Scrollable Panel. You should be able to toggle between FIT and STRETCH.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • 1
    +1 for a very good answer that worked; however I am trying to toggle the text wrapping, and have updated the question. Sorry for the bad question. – GlassGhost Jan 16 '11 at 07:27
10
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 don't know any other way for what you are looking for..

But this is working well.


( Based on camickr's answer.. +1 )

Stefanos Kalantzis
  • 1,619
  • 15
  • 23