如何计算在JTextArea行数,包括那些引起包装? [英] How to count the number of lines in a JTextArea, including those caused by wrapping?

查看:258
本文介绍了如何计算在JTextArea行数,包括那些引起包装?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我已经设置自动换行,敷式的字为true的JTextArea中。我想包中的JTextArea到最小可能的高度给予了指定的宽度。

要做到这一点,我打算计算字体的使用高度...

 字体的字体= jTextArea.getFont();
  FontMetrics对象的FontMetrics = jTextArea.getFontMetrics(字体);
  INT lineHeight是= fontMetrics.getAscent()+ fontMetrics.getDescent();

...然后通过在JTextArea中所使用的行数乘以。问题是,JTextArea.getLineCount()计算行返回忽略换行的数量。

我如何计数,包括那些由词引起裹JTextArea中使用的行数?

下面是一些演示code,使这个问题更容易玩弄。我有每个窗口大小时打印出的行数的监听器。目前,它总是打印1,但我想,以补偿自动换行,并打印出有多少行的实际使用。

编辑:我已经包括在下面的code中的问题的解决方案。静态countLines方法给出了解决方案。

 套装部件;进口java.awt中的*。
java.awt.event中导入*。
导入的java.awt.font *。
导入的java.text *。
进口的javax.swing *。公共类JTextAreaLineCountDemo继承JPanel {
  JTextArea中textarea的;  公共JTextAreaLineCountDemo(){
    超级(新的GridBagLayout());    字符串inputStr =Lorem存有悲坐阿梅德,consectetur adipisicing ELIT,SED eiusmo做;
    TEXTAREA =新的JTextArea(inputStr);
    textArea.setEditable(假);
    textArea.setLineWrap(真);
    textArea.setWrapStyleWord(真);    //添加组件此面板。
    GridBagConstraints的C =新的GridBagConstraints();
    c.gridwidth = GridBagConstraints.REMAINDER;    c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    c.weighty = 1.0;
    加(TEXTAREA,C);    addComponentListener(新ComponentAdapter(){
      @覆盖
      公共无效的componentResized(ComponentEvent CE){
        的System.out.println(行数:+ countLines(TEXTAREA));
      }
    });
  }  私有静态诠释countLines(TEXTAREA的JTextArea){
    AttributedString文本=新AttributedString(textArea.getText());
    FRC的FontRenderContext = textArea.getFontMetrics(textArea.getFont())
        .getFontRenderContext();
    的AttributedCharacterIterator charIt = text.getIterator();
    LineBreakMeasurer构造lineMeasurer =新LineBreakMeasurer构造(charIt,FRC);
    浮动formatWidth =(浮点)textArea.getSize()宽。
    lineMeasurer.setPosition(charIt.getBeginIndex());    INT noLines = 0;
    而(lineMeasurer.getPosition()&所述; charIt.getEndIndex()){
      lineMeasurer.nextLayout(formatWidth);
      noLines ++;
    }    返回noLines;
  }  私有静态无效createAndShowGUI(){
    JFrame的帧=新的JFrame(JTextAreaLineCountDemo);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    frame.add(新JTextAreaLineCountDemo());    frame.pack();
    frame.setVisible(真);
  }  公共静态无效的主要(字串[] args){
    javax.swing.SwingUtilities.invokeLater(新的Runnable(){
      公共无效的run(){
        createAndShowGUI();
      }
    });
  }
}


解决方案

您可以使用<一个href=\"http://download.oracle.com/javase/6/docs/api/java/awt/font/LineBreakMeasurer.html\"><$c$c>LineBreakMeasurer类。


  

该LineBreakMeasurer构造类允许
  样式化的文本断为行
  (或段),以符合内的
  尤其是可视advance。这是
  谁希望显示的客户有用
  文本段落内的配合
  特定宽度,称为包装
  width.LineBreakMeasurer实现最常用的换行政策:每
  字包装内的配合
  宽度被放置在线路。如果
  第一个单词不适合,那么所有的
  适合内的字符
  缠绕宽度被放置在线路。
  至少一个字符被放置在
  每一行。


I have a JTextArea for which I have set word-wrap and wrap-style-word to true. I want to "pack" the JTextArea to the minimum possible height given a specified width.

To do this, I'm planning calculating the height of the font using...

  Font font = jTextArea.getFont();
  FontMetrics fontMetrics = jTextArea.getFontMetrics(font);
  int lineHeight = fontMetrics.getAscent() + fontMetrics.getDescent();

...and then multiply this by the number of lines used in the JTextArea. The problem is that JTextArea.getLineCount() counts the number of line returns ignoring the wrapped lines.

How do I count the number of lines used in a JTextArea including those that are caused by word wrap?

Here's some demo code to make toying with this problem easier. I have a listener that prints out the number of lines each time the window is resized. At the moment, it always prints 1, but I want to to compensate for the word wrap and print out how many lines are actually being used.

EDIT: I've included the solution to the problem in the code below. The static countLines method gives the solution.

package components;                                                                           

import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.text.*;
import javax.swing.*;

public class JTextAreaLineCountDemo extends JPanel {                                          
  JTextArea textArea;                                                                         

  public JTextAreaLineCountDemo() {                                                           
    super(new GridBagLayout());                                                               

    String inputStr = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmo";
    textArea = new JTextArea(inputStr);                                                       
    textArea.setEditable(false);                                                              
    textArea.setLineWrap(true);                                                               
    textArea.setWrapStyleWord(true);                                                          

    // Add Components to this panel.                                                          
    GridBagConstraints c = new GridBagConstraints();                                          
    c.gridwidth = GridBagConstraints.REMAINDER;                                               

    c.fill = GridBagConstraints.BOTH;                                                         
    c.weightx = 1.0;                                                                          
    c.weighty = 1.0;                                                                          
    add(textArea, c);                                                                         

    addComponentListener(new ComponentAdapter() {                                             
      @Override                                                                               
      public void componentResized(ComponentEvent ce) {                 
        System.out.println("Line count: " + countLines(textArea));                         
      }                                                                                       
    });                                                                                       
  }                                                                                           

  private static int countLines(JTextArea textArea) {
    AttributedString text = new AttributedString(textArea.getText());
    FontRenderContext frc = textArea.getFontMetrics(textArea.getFont())
        .getFontRenderContext();
    AttributedCharacterIterator charIt = text.getIterator();
    LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(charIt, frc);
    float formatWidth = (float) textArea.getSize().width;
    lineMeasurer.setPosition(charIt.getBeginIndex());

    int noLines = 0;
    while (lineMeasurer.getPosition() < charIt.getEndIndex()) {
      lineMeasurer.nextLayout(formatWidth);
      noLines++;
    }

    return noLines;
  }

  private static void createAndShowGUI() {                                                    
    JFrame frame = new JFrame("JTextAreaLineCountDemo");                                      
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                                     

    frame.add(new JTextAreaLineCountDemo());                                                  

    frame.pack();                                                                             
    frame.setVisible(true);                                                                   
  }                                                                                           

  public static void main(String[] args) {                                                    
    javax.swing.SwingUtilities.invokeLater(new Runnable() {                                   
      public void run() {                                                                     
        createAndShowGUI();                                                                   
      }                                                                                       
    });                                                                                       
  }                                                                                           
}                                                                                             

解决方案

You can use LineBreakMeasurer Class.

The LineBreakMeasurer class allows styled text to be broken into lines (or segments) that fit within a particular visual advance. This is useful for clients who wish to display a paragraph of text that fits within a specific width, called the wrapping width.LineBreakMeasurer implements the most commonly used line-breaking policy: Every word that fits within the wrapping width is placed on the line. If the first word does not fit, then all of the characters that fit within the wrapping width are placed on the line. At least one character is placed on each line.

这篇关于如何计算在JTextArea行数,包括那些引起包装?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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