我正在尝试创建一个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:


固定宽度
可以从初始值动态扩展的高度,
尺寸与框架尺寸无关,
对JTextPane内容有反应的滚动条,但是放置在框架的内侧而不是JTextPane的边缘


当通过行数和列数创建TextArea并启用换行和单词时,则它的工作方式与我想要的完全相同-但不适用于JTextPane。

我试过了:


在JScrollPane中添加JTextPane-但是JTextPane使用JScrollPane更改其大小,
JTextPane的setPrefferedSize-但它不会水平扩展,
在JPanel上插入带有JTextPane的JScrollPane,然后将JPanel添加到另一个JScrollPane-看起来非常糟糕,

第一个答案的解决方案-这取决于我的使用方式,它要么给出固定的宽度和高度,要么两者都是可变的,



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

最佳答案

您将需要重写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不支持行/列大小的概念,因此您将需要添加自己的逻辑以得出默认的首选大小。

使用硬编码值,我想到了以下代码来复制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;
    }
};

09-10 07:28
查看更多