如何在 JTextArea 行计数中考虑换行?

2024-05-12

我知道这一点thread https://stackoverflow.com/questions/6366776/how-to-count-the-number-of-lines-in-a-jtextarea-including-those-caused-by-wrapp展示了一种方法,但在我的情况下它会导致奇怪的行为,我想知道是否没有simpler方法来做到这一点。

我需要知道我的尺码JTextArea设置文本后就会有。这是我现在的做法:

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

除非没有换行,否则它会起作用。我想对换行进行相同的计算。有谁知道什么时候会发生换行吗?这样我只需要将当前行数增加一即可。

EDIT:

这是(也许)我找到的解决方案。几乎是复制粘贴this http://www.exampledepot.com/egs/javax.swing/screen_ScreenCoords.html作者:@camickr。

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

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


在我看来,只要你还没有打完电话setPreferredSize在文本区域上,getPreferredSize方法应该可以准确地为您提供您正在寻找的内容,而无需麻烦......

这就是为什么你不应该打电话的原因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);
    }

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 JTextArea 行计数中考虑换行? 的相关文章

随机推荐