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