java - 如何计算 JTextArea 中的行数,包括由换行引起的行数?

标签 java textarea awt jtextarea

我有一个 JTextArea,我已将 word-wrap 和 wrap-style-word 设置为 true。在给定指定宽度的情况下,我想将 JTextArea“打包”到可能的最小高度。

为此,我计划使用...计算字体的高度

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

...然后将其乘以 JTextArea 中使用的行数。问题是 JTextArea.getLineCount() 计算返回的行数而忽略换行。

如何计算 JTextArea 中使用的行数,包括由自动换行引起的行数?

这里有一些演示代码可以更轻松地解决这个问题。我有一个监听器,每次调整窗口大小时都会打印出行数。目前,它总是打印 1,但我想补偿自动换行并打印出实际使用了多少行。

编辑:我在下面的代码中包含了问题的解决方案。静态 countLines 方法给出了解决方案。

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

最佳答案

您可以使用 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.

关于java - 如何计算 JTextArea 中的行数,包括由换行引起的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6366776/

相关文章:

java - log4j2 动态变量的默认值

javascript - 在js中重新启用对键盘的访问

java - JFrame 不显示输出?

java - Android 按钮的动画效果不符合预期

java - 一个类必须遵守一个接口(interface)的文档约定才能说实现该接口(interface)

javascript - 当用户在搜索栏上键入内容时,如何显示/隐藏文本区域值?

css - CodeMirror(JS代码高亮)textarea中的文字超出textarea宽度

java - 使用 AWT 将标签设置为 ActionPerformed 内可见

java - 线程 "AWT-EventQueue-0"java.lang.NullPointerException 中出现异常 [NetBeans]

java - 这个程序的效率如何?