【问题标题】:Fixing the Size of JEditorPane inside a JPanel修复 JPanel 中 JEditorPane 的大小
【发布时间】:2011-12-16 08:56:58
【问题描述】:

这与我的上一个问题非常相似,但是在 JPanel 中执行此操作我试图在 JPanel(固定大小)内显示 JEditorPane,然后显示一串 HTML 文本。 (这样我就可以使用卡片布局并切换具有不同显示器的面板)。我可以再次显示所有内容,尽管我传递给 EditorPane 的 HTML 字符串中的文本似乎没有切断并换行。即它只是延伸到屏幕之外。 好像setSize方法对Pane的大小没有影响?

我正在为不同尺寸的屏幕制作这个应用程序,因此文本换行并适合屏幕尺寸而不是流失很重要!当 EditorPane 直接位于 JFrame 而不是 JPanel 时,它可以工作。

    JEditorPane pane = new JEditorPane();
    pane.setEditable(false);
    HTMLDocument htmlDoc = new HTMLDocument () ; 
    HTMLEditorKit editorKit = new HTMLEditorKit () ;
    pane.setEditorKit (editorKit) ; 
    pane.setSize(size);
    pane.setMinimumSize(size); 
    pane.setMaximumSize(size);
    pane.setOpaque(true);
    pane.setText("<b><font face=\"Arial\" size=\"50\" align=\"center\" > Unfortunately when I display this string it is too long and doesn't wrap to new line!</font></b>");
    bg.add(pane, BorderLayout.CENTER);

非常感谢山姆

【问题讨论】:

标签: java swing layout-manager jeditorpane


【解决方案1】:

好吧,你永远不要在你的应用程序中使用 setXXXSize 方法。看到这个thread

只是一些注意事项:

  1. 这取决于 LayoutManager 的定位并确定组件的正确大小,因此您不应明确指定它
  2. 并非所有 LayoutManager 都会处理组件的 preferredSize 值。
  3. 即使 LayoutManager 处理首选大小,显式使用这些方法也是错误的
  4. 如果您想明确使用尺寸,请仅使用包含所有组件的父框架。
  5. 如果 LayoutManager 没有以正确的方式放置组件,请使用不同的 LayoutManager 或实现您自己的。

备注:

我知道在某些情况下使用 setXXXmethods 似乎可以正常工作。我这样做了很长时间,才明白它有多大的错误。尽量避免这种情况,否则迟早会有大量代码需要重构。

【讨论】:

    【解决方案2】:
    ..."Unfortunately when I display this string it is too long and doesn't wrap to new line!"
    

    使用 body 元素中的样式设置宽度,如 this example

    【讨论】:

    • +1 好吧,这是正确的答案。实际上,我的只是关于为什么不使用 setXXXSize 的建议。
    猜你喜欢
    • 2011-12-16
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多