gpt4 book ai didi

java - 如何修复 JScrollPane 内 JEditorPane 的高度?

转载 作者:行者123 更新时间:2023-11-30 03:17:56 27 4
gpt4 key购买 nike

我想将 JScrollPane 内的 JEditorPane 的高度限制为最大值,但仍允许宽度扩展以适合内容。

我这样做的原因是我想要一行文本来允许我嵌入组件。我真的想要像带有可嵌入组件的 JTextField 这样的东西,但由于 JTextField 无法做到这一点,所以我使用 JEditorPane (JTextPane 也可以)。

我正在尝试模仿桌面 Swing 应用程序中的 StackOverflow 标记行为。因此,我将在 JEditorPane 中嵌入可点击的“标签”,它们将全部显示在一行中,就像 SO 所做的那样。

就目前情况而言,JEditorPane 会垂直扩展,但不会使用此 SSCCE 水平扩展:

import javax.swing.*;
import java.awt.BorderLayout;

public class Tags {
/*
* This is the method I want to modify to implement this behavior:
*/
public static JComponent buildTagsComponent() {
JScrollPane scrollPane = new JScrollPane();
JEditorPane editorPane = new JEditorPane();
scrollPane.setViewportView(editorPane);
return scrollPane;
}
/*
* The remainder of this code is just to make the example complete.
*/
public static JFrame buildFrame() {
JFrame frame = new JFrame("Tags example");
JPanel panel = new JPanel();
JPanel tagsPanel = new JPanel();
JLabel tagsLabel = new JLabel("Tags:");
JLabel mainContent = new JLabel("Main Content Goes Here");
tagsPanel.add(tagsLabel);
tagsPanel.add(buildTagsComponent());
panel.setLayout(new BorderLayout());
panel.add(tagsPanel,BorderLayout.SOUTH);
panel.add(mainContent,BorderLayout.CENTER);
frame.setContentPane(panel);
return frame;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
JFrame frame = buildFrame();
frame.pack();
frame.setVisible(true);
}
}
);
}
}

另请注意,我计划禁用滚动条并需要使用手势滚动或使用光标键移动光标位置。当我为滚动条策略添加“从不”时,这只会使事情根本无法滚动。我现在并不是在寻找滚动问题的解决方案,我只是希望答案考虑到我将水平和垂直的滚动条策略设置为“从不”。

我尝试将高度和宽度(最小值、首选值和最大值)分别显式设置为 12 和 Integer.MAX_VALUE

更新

经过一些研究,我相信我正在寻找的解决方案与自动换行有关。我希望 JEditorPane 在没有换行符(换行)时不换行。

最佳答案

目前,由于布局管理器的原因,编辑器 Pane 无法水平调整大小。 JPanel 的默认值是 FlowLayout ,它按照固定的首选大小调整组件的大小。

尝试 BoxLayout :

JPanel tagsPanel = new JPanel();
tagsPanel.setLayout(new BoxLayout(tagsPanel, BoxLayout.LINE_AXIS));
// then add components

额外提示:要改善面板的外观,您可以添加不可见组件(在其他组件之间放置空间)和/或空边框(与其他组件创建边距:

tagsPanel.add(tagsLabel);
tagsPanel.add(Box.createRigidArea(new Dimension(10,0)));
tagsPanel.add(buildTagsComponent());
tagsPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

<小时/>关于换行问题(与 JTextArea 不同,在 JEditorPane 中无法轻松停用),提出了一个解决方案 here (引用自 this post)。

基本上,您必须扩展 StyledEditorKit 并将其设置为您的 JEditorPane

<小时/>关于 JScrollPane 的行为,也许解决方案是使用 AS_NEEDED 默认设置,但是 customize the UI of the scroll bars使它们的大小等于零。这样您就可以在没有滚动条本身的情况下实现滚动行为。

关于java - 如何修复 JScrollPane 内 JEditorPane 的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32102707/

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