【问题标题】:How to take line wrap in account for JTextArea line counting?如何为 JTextArea 行计数考虑换行?
【发布时间】:2012-10-11 10:33:53
【问题描述】:

我知道这个thread 显示了一种方法,但在我的情况下它会导致奇怪的行为,我想知道是否没有更简单的方法来做到这一点。

我需要知道我的JTextArea 设置文本后的大小。这是我目前的做法:

tarea.getLineCount() * tarea.getRowHeight();

除非没有换行,否则它可以工作。我想用换行做同样的计算。有没有人知道何时发生换行?这样我只需要将当前行数加一。

编辑:

这是(也许)我找到的解决方案。这几乎是@camickr 对this 的复制粘贴。

int rowStartOffset = textComponent.viewToModel(new Point(0, 0));
int endOffset = textComponent.viewToModel(new Point(0, textComponent.getHeight()));

int count = 0; //used to store the line count
while (rowStartOffset < endOffset) {
    try {
        rowStartOffset = Utilities.getRowEnd(textComponent, rowStartOffset) + 1;
    } catch (BadLocationException ex) {
        break;
    }
    count++;
}

我在启用/不启用换行的情况下做了一些测试,它似乎有效。

【问题讨论】:

  • 如果不是用于编辑,使用多行JLabel
  • 有人会为此把你钉在十字架上:-)
  • @mKorbel 有多认真?我做错了什么?但是谢谢,我会考虑使用多行 jlabel。
  • 在此之前您可以阅读并尝试@camickr 的Text Component Line Number
  • @mKorbel 这真的取决于 OP 试图实现的目标。如果他们没有说明该区域是否需要编辑,我只是​​在猜测。

标签: java swing jtextarea


【解决方案1】:

在我看来,只要您没有在文本区域上调用 setPreferredSizegetPreferredSize 方法应该可以轻松地为您提供所需的内容...

这就是为什么你不应该调用setPreferredSize 来做布局的原因。首选大小应该由组件计算(例如设置文本时)。

如果我遗漏了要点,请告诉我;)

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class CalculateTextAreaSize extends Box{

    public CalculateTextAreaSize(){
        super(BoxLayout.Y_AXIS);

        final JTextArea text = new JTextArea("I've\nGot\nA\nLovely\nBunch\nof\nCoconuts!\n");

        JScrollPane pane = new JScrollPane(text);

        add(pane);

        JButton button = new JButton("Set Text!");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                text.insert("Longish string - how long will it be?", text.getDocument().getLength());
                //The size it will be once everything is figured out
                System.out.println(text.getPreferredSize());
                //The size it is now because no rendering has been done
                System.out.println(text.getSize());
            }
        });
        add(button);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new CalculateTextAreaSize());
        frame.validate();
        frame.pack();
        frame.setVisible(true);
    }

}

【讨论】:

    猜你喜欢
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多