使用 putConstraint 的 Spring 布局中 TextArea 的动态高度 - Java

Dynamic height of TextArea in Spring Layout using putConstraint - Java

我想在文本区域中以动态高度显示注释(有些注释很小,有些注释很长)。 我正在从 textarea 中检索注释行以定义布局中的高度。 我尝试了不同的布局,但没有成功。 (意思是,根据音符长度正确设置了不同的高度,但在 GUI 中,所有音符高度均匀分布。)

这一次,我正在尝试Springlayout,看看它是否更好,但我没有取得太大进展。我不太确定在我的情况下我是否正确使用了 putConstraint() 。

    TextArea textArea = new JTextArea();
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    ComponentUtils.setComponentText(textArea, note.getDisplayLines());

    int height= textArea.getLineCount(); 

    JPanel innerPanel = new JPanel();
    SpringLayout layout = new SpringLayout();
    innerPanel.setLayout(layout);
    innerPanel.add(textArea);
    layout.putConstraint(SpringLayout.NORTH, textArea,
            5, SpringLayout.NORTH, innerPanel);

    outerPanel.add(innerPanel , BorderLayout.CENTER);

我找到了解决我自己问题的方法。 至于布局,GridBagLayout 非常适合创建不同大小的 JTextArea 高度。 (当使用其他布局时,它们默认均匀分布高度,这对我来说是个问题。)

使用GridBagLayout时,需要实例化GradBagConstraints。 有了对象,就可以调用内置函数; fill、weightx、gridx、gridwith 等,以满足您在 GUI 中的个人需求。