【发布时间】:2012-01-02 11:28:57
【问题描述】:
JEditorPane 似乎有一个非常有趣的功能:它似乎跟踪其父级宽度,并相应地确定首选高度,如果父级不是JViewport。
轨道我的意思是组件的首选宽度设置为其父级之一(可能除了一些插图之外)。 ScrollableTracksViewportWidth 是假的。
这是演示这一事实的非常简单的代码(只需复制和修复导入):
调整 JFrame 的大小时,JEditorPane(在我的环境中)的首选宽度始终为 frame.width-14(当然 14 可能是图形系统特定的)。
q1) 跟踪父级(非视口)宽度很好。我可以依靠它吗?据我所知,这是一个未记录的功能。更多!只需将new JEditorPane() 替换为new JTextPane(),这是JEditorPane 的更丰富的子类,该功能就会消失。
q2) 在我看来,这种“跟踪”是通过 JEditorPane 大小的“设置”发生的。这意味着首先必须设置尺寸(宽度),然后首选尺寸高度就可以了。这样对吗?
q3) 为什么JTextPane没有这个功能?
public class SSCE01 extends JFrame {
public static void main(String[] a) {
new SSCE01().setVisible(true);
}
public SSCE01() {
final JEditorPane ep = new JEditorPane();
add(ep);
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
Dimension ps = getSize();
System.out.println("Frame size : " + ps.width + " x " + ps.height);
ps = ep.getPreferredSize();
System.out.println("JEditorPane preferredSize: " + ps.width + " x " + ps.height);
}
});
pack();
}
}
q4) 更明确的问题。正如 q2 中假设的那样,设置大小允许跟踪。但仅适用于 JEditorPane,不适用于 JTextPane。我怎样才能为 JTextPane 完成这个呢?
这行得通:
public SSCE02() {
JEditorPane ep = new JEditorPane();
ep.setText("this is a very very long text. veeeeery long, so long that it will never fit into one 100 pixels width row");
ep.setSize(new Dimension(100,Integer.MAX_VALUE));
add(ep);
pack();
}
这不是。它已被使用JTextPane 代替JEditorPane:
public SSCE02() {
JEditorPane ep = new JTextPane();
ep.setText("this is a very very long text. veeeeery long, so long that it will never fit into one 100 pixels width row");
ep.setSize(new Dimension(100,Integer.MAX_VALUE));
add(ep);
pack();
}
更新 1
摘要:在 JEditorPane 中观察到“轨道大小属性”,但在 JTextPane 中不存在类似的情况。
稍微但意义重大的一步:
将 HTML 文档加载到 JEditorPane 中也会使该功能从 JEditorPane 中消失。
此时,该功能似乎是由 Document 实现而不是由 JEditorPane(或 JTextPane)本身实现的!对于 JEditorPane,文档是 javax.swing.text.PlainDocument。当你这样做时:
URL url = HTMLInComponents01.class.getResource("sample.html");
jEditorPane1.setPage(url);
System.out.println(jEditorPane1.getDocument().getClass().getName());
你会得到:
javax.swing.text.html.HTMLDocument
我还注意到良好的javax.swing.text.PlainDocument 为我们提供了“在通过 setSize 给出宽度时“计算组件的高度”这一出色服务”不能分配给需要 StyledDocument 实例的 JTextPane!
现在我将验证哪些其他文本组件能够使用PlainDocument。
【问题讨论】:
-
能否提供“TextPanePerfectSize”的网址?
标签: java swing layout jtextpane jeditorpane