Word Wrapping not working in JTextArea

可紊 提交于 2019-12-11 06:31:54

问题


The word wrapping method provided for JTextArea is not working in my program. Why isn't it working? How can I fix it? Here is the code:

    text= new JTextArea(15,65);

    text.setWrapStyleWord(true); // word wrapping enabled

    text.setPreferredSize(new Dimension(getPreferredSize()));

Here is the screenshot. The last word goes out of frame.


回答1:


The following SSCCE let you experiment with both settings. Here you can see that using setWrapStyleWord has no effect if you do not call setLineWrap first. This is also documented in the javadoc of setWrapStyleWord.

The best results for a readable form is setting them both to true.

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class TextAreaDemo {

  public static void main( String[] args ) {
    EventQueue.invokeLater( new Runnable() {
      @Override
      public void run() {
        JFrame testFrame = new JFrame( "TestFrame" );

        final JTextArea textArea = new JTextArea( 15, 65 );
        testFrame.add( new JScrollPane( textArea ) );

        final JCheckBox wordWrap = new JCheckBox( "word wrap" );
        wordWrap.setSelected( textArea.getWrapStyleWord() );
        wordWrap.addItemListener( new ItemListener() {
          @Override
          public void itemStateChanged( ItemEvent e ) {
            textArea.setWrapStyleWord( wordWrap.isSelected() );
          }
        } );
        testFrame.add( wordWrap, BorderLayout.NORTH );
        final JCheckBox lineWrap = new JCheckBox( "line wrap" );
        lineWrap.setSelected( textArea.getLineWrap() );
        lineWrap.addItemListener( new ItemListener() {
          @Override
          public void itemStateChanged( ItemEvent e ) {
            textArea.setLineWrap( lineWrap.isSelected() );
          }
        } );
        testFrame.add( lineWrap, BorderLayout.SOUTH );

        testFrame.pack();
        testFrame.setDefaultCloseOperation( WindowConstants.DISPOSE_ON_CLOSE );
        testFrame.setVisible( true );
      }
    } );

  }
}


来源:https://stackoverflow.com/questions/13441363/word-wrapping-not-working-in-jtextarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!