java - 如何将 JTextPane 的首选大小设置为其内容大小?

标签 java swing jtextpane preferredsize

我有一个带有 Boxlayout 的 JPanel 以及一些将动态添加到其中的 JTextPanes 和 JPanel。我想设置 JTextPanes 的首选大小以适合其内容。我将 StyledDocument 用于 JTextPane。我怎样才能做到这一点?

编辑: 当我创建一个新的 JTextPane 时,我拥有它的内容并且它不会改变。这是我的代码:

public void display(final String text){
    StyleContext sc = new StyleContext();
    final DefaultStyledDocument doc = new DefaultStyledDocument(sc);
    Style defaultStyle = sc.getStyle(StyleContext.DEFAULT_STYLE);
    final Style style = sc.addStyle("MainStyle", defaultStyle);
    JTextPane pane = new JTextPane(){
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        @Override
        public Dimension getMinimumSize(){
            return new Dimension(text.length()*5, getContentHeight(text.length()*5,text));
        }
        @Override 
        public Dimension  getMaximumSize(){
            return  new Dimension(430, getContentHeight(text.length()*5,text));
        }
    };
    receive.setStyledDocument(doc);
    receive.setEditable(false);
    receive.setPreferredSize(new Dimension(text.length()*5, getContentHeight(text.length()*5,text)));
    
    try {
        doc.insertString(doc.getLength(),text,style);
    } catch (BadLocationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Jpanel.add(pane);
    
}

public int getContentHeight(int i, String content) {
        JEditorPane dummyEditorPane=new JEditorPane();
        dummyEditorPane.setSize(i,Short.MAX_VALUE);
        dummyEditorPane.setText(content);
        return dummyEditorPane.getPreferredSize().height;
    }

问题出在 getMinimumSize()getMaximumSize()setPreferredSize() 方法中!同样在我为 dummyEditorPane.setSize(i,Short.MAX_VALUE); 设置的宽度中; 如何为 JTextPane 设置固定大小?

最佳答案

JScrollPane内添加JTextPane以适合其内容。如果它不起作用,则重写 getPreferredSize() 以根据需要设置首选大小。

 @Override
 public Dimension getPreferredSize() {
     return new Dimension(..., ...);
 }

请参阅 How to Use Editor Panes and Text Panes 上的 Swing 教程例如。

关于java - 如何将 JTextPane 的首选大小设置为其内容大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24893073/

相关文章:

java - 连接 2 个字节数组,然后转换为音频流

java - 构建泛型类

java - 如何将 BufferedImage 绘制到 JPanel

java - 使用 Swing 在 Java 中以粗体书写

java - JTextPane 中的插入符位置不正确?!错误或预期的行为?

java - 更新单词的属性集时,它会在 JTextPane 中抛出 IllegalStateException

java - 为什么有时我们必须在 Android 中调用 super ?

java - OffsetDateTime 在 GET 方法中产生 "No injection source found for a parameter of type public javax.ws.rs.core.response"

java - 使用 fireTableRowsInserted(int,int) 更新模型和 JTable

java - 通过以缓冲区居中来保持组件尺寸