一个单向展开的 JTextPane

An one-directional expanding JTextPane

我正在尝试创建一个 JTextPane,它将像下面示例中的 JTextArea 一样工作:

import javax.swing.*;
import java.awt.*;

public class SampleTextArea {
    public static void main(String[] args){
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        JTextArea textArea = new JTextArea(72,75);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        panel.add(textArea);
        JScrollPane scrollPane = new JScrollPane(panel);
        frame.getContentPane().add(BorderLayout.CENTER, scrollPane);

        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(1200,600);
        frame.setVisible(true);
    }
}

我想用以下内容创建 JTextPane:

当 TextArea 是按行数和列数创建的,并且启用换行和换行时,它的工作方式与我想要的完全一样 - 但它不适用于 JTextPane。

我试过了:

如有任何建议,我将不胜感激。

当您制作 JTextArea 时,您将 72,75 作为行和列,JTextArea(int rows, int columns)(来自 api)尝试减少该数字并它应该工作。

您需要覆盖 JTextPane 的 getPreferredSize() 才能实现您的要求。

可以先看看JTextArea的getPreferredSize()方法:

public Dimension getPreferredSize() {
    Dimension d = super.getPreferredSize();
    d = (d == null) ? new Dimension(400,400) : d;
    Insets insets = getInsets();

    if (columns != 0) {
        d.width = Math.max(d.width, columns * getColumnWidth() +
                insets.left + insets.right);
    }
    if (rows != 0) {
        d.height = Math.max(d.height, rows * getRowHeight() +
                            insets.top + insets.bottom);
    }
    return d;
}

JTextPane 不支持 row/column 大小的概念,因此您需要添加自己的逻辑来得出默认的首选大小。

使用硬编码值,我想出了以下复制 JTextArea 行为的内容:

JTextPane textArea = new JTextPane()
{
    @Override
    public Dimension getPreferredSize()
    {
        Dimension d = super.getPreferredSize();
        d = (d == null) ? new Dimension(400,400) : d;
        Insets insets = getInsets();

        d.width = Math.max(d.width, 300 + insets.left + insets.right);
        d.height = Math.max(d.height, 300 + insets.top + insets.bottom);

        return d;
    }
};