无法在 JDialog 内的 JScrollPane 内设置 JEditorPane 的最大高度

Cannot set maximum height of JEditorPane inside JScrollPane inside JDialog

所以我想实现一些非常简单的东西。 在我的应用中,用户可以查阅一些文件的内容。 首先,文件的内容在HTML里,所以我用JEditorPane来显示。其次,文件内容有点长。因为我希望它可以滚动,所以我将它包装在 JScrollPane 中。最后,这个 window 应该是模态的。所以我再次将它包装在 JDialog 中。这是我的代码:

JEditorPane ep = new JEditorPane();
ep.setContentType("text/html");
ep.setEditable(false);
ep.setText(longHtmlString);
        
JScrollPane sp = new JScrollPane(ep);
sp.getViewport().setPreferredSize(new java.awt.Dimension(500, 1500));
        
JDialog dialog = new JDialog();
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.getContentPane().add(sp);
dialog.setModal(true);
dialog.setResizable(false);
dialog.pack();

dialog.setVisible(true);

但这是我得到的输出: Output

如您所见,没有滚动条,对话框只占 HTML 内容的整个高度...我希望对话框具有固定高度和垂直滚动条。内容将始终像屏幕截图上一样长。我已经尝试在 3 个组件(editorpane、scrollpane、jdialog)中的任何一个上设置大小,但我无法实现我想要的。我错过了什么吗?

您的对话框将是 模态,因此请确保将对话框设置为始终位于其他对话框之上 windows:

dialog.setAlwaysOnTop(true);

显示与特定 Window 或组件相关的对话框。如果您希望对话框显示在监视器屏幕的中央,则使其相对于 null:

显示
........
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);

在这种特殊情况下,您可以在最终组件级别设置事物的首选大小,但稍后您最终会发现这可能会导致一些不良结果。将对话框设置为您想要的大小,然后让 pack() 处理其余的事情:

dialog.setPreferredSize(new java.awt.Dimension(500, 400));

正如@camickr 在评论中提到的那样,将尺寸设置为更真实的尺寸。 1500 的高度设置有点大,但我确定这是一个错字,您的实际意图是 500, 500

如果您要为对话框设置一个标题栏(大多数情况下都是这样做的),那么最好在其中设置一个实际的标题以指示显示内容的内容:

dialog.setTitle("Would be nice to have a title here... - longHtmlString");

设置滚动条窗格的水平垂直策略,以便组件知道预期的内容:

sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

通过以上设置,将显示任一滚动条如果需要它们。

有时,能够稍微调整 window 的大小以捕获超出限制的数据,而不是一直使用滚动条,这真是太好了。您可能需要考虑删除 dialog.setResizable(false); 行代码,以便确实可以根据需要调整对话框的大小。

为了让放置在 JEditorPane 中的文本 material 从文档的顶部而不是文档的底部开始显示,您可能需要考虑将插入符号位置移动到索引位置 0.是的,即使编辑器窗格设置为 non-editable:

也能正常工作
ep.setCaretPosition(0);

以下应该工作正常:

// The JDialog Window...
JDialog dialog = new JDialog();
dialog.setTitle("Would be nice to have a title here... - longHtmlString");
dialog.setAlwaysOnTop(true);
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.setPreferredSize(new java.awt.Dimension(500, 400));
dialog.setModal(true);
//dialog.setResizable(false);
    
// The JEditorPane...
JEditorPane ep = new JEditorPane();
ep.setContentType("text/html");
ep.setEditable(false);
ep.setText(longHtmlString);
ep.setCaretPosition(0);

// The JScrollPane...
JScrollPane sp = new JScrollPane(ep);     // Declared JEditorPane added here.
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

// Add components to dialog, pack it, and display the dialog.
dialog.getContentPane().add(sp);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);