Word Wrapping在JTextArea中不起作用 [英] Word Wrapping not working in JTextArea

查看:76
本文介绍了Word Wrapping在JTextArea中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为JTextArea提供的自动换行方法在我的程序中不起作用.为什么不起作用?我该如何解决?这是代码:

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.

推荐答案

以下SSCCE可以让您尝试这两种设置.在这里您可以看到,如果不先调用setLineWrap,则使用setWrapStyleWord无效.这也记录在setWrapStyleWord的javadoc中.

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.

可读形式的最佳结果是将它们都设置为true.

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 );
      }
    } );

  }
}

这篇关于Word Wrapping在JTextArea中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆