我正在尝试在垂直 BoxLayout 中使用多行标签和图像标签。对于多行标签,我使用带有 setEditable(false) 的 JTextArea。对于图像标签,我使用 JLabel([ImageIcon])。
以下代码显示 textarea 下面有很多空间,我不希望这样。为了简单起见,我添加了文本标签而不是图像标签。
我想要的是从上到下堆叠文本区域和标签。在每个 textarea 之后,标签应该紧跟在下面,在最后一个标签之后,到窗口底部应该有空白空间。
也许另一个布局管理器更好,但我认为这是一个 JTextArea 问题。任何解决方案都会有所帮助。
谢谢。
这是可编译的代码:
import java.awt.Color;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
public class BoxLay extends JFrame
{
private static final long serialVersionUID = 1L;
public static void main(final String[] args)
{
new BoxLay();
}
private BoxLay()
{
setTitle("BoxLayout TestDummy");
setSize(800, 450);
setResizable(true);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.getContentPane().setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
final JTextArea area1 = new JTextArea();
area1.setText("First Text - Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... ");
area1.setLineWrap(true);
area1.setWrapStyleWord(true);
area1.setEditable(false);
area1.setBackground(Color.RED);
this.add(area1);
final JLabel label1 = new JLabel("DIRECTLY BELOW FIRST TEXT");
this.add(label1);
final JTextArea area2 = new JTextArea();
area2.setText("Second Text - Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... Dynamic text of any length... ");
area2.setLineWrap(true);
area2.setWrapStyleWord(true);
area2.setEditable(false);
area2.setBackground(Color.RED);
this.add(area2);
final JLabel label2 = new JLabel("DIRECTLY BELOW SECOND TEXT");
this.add(label2);
this.add(Box.createVerticalGlue());
this.getContentPane().invalidate();
this.getContentPane().validate();
}
}