gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:48:59 24 4
gpt4 key购买 nike

我有一个带有 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com