我想创建一个包含某些文本元素(JLabel/JTextArea等)的对话框,该文本元素多行并包装单词。我希望对话框的宽度固定,但根据文字的大小来调整高度。我有这样的代码:获取具有固定宽度的多行文本的高度,以便正确调整对话框的大小
import static javax.swing.GroupLayout.DEFAULT_SIZE;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TextSizeProblem extends JFrame {
public TextSizeProblem() {
String dummyString = "";
for (int i = 0; i < 100; i++) {
dummyString += " word" + i; //Create a long text
}
JLabel text = new JLabel();
text.setText("<html>" + dummyString + "</html>");
JButton packMeButton = new JButton("pack");
packMeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pack();
}
});
GroupLayout layout = new GroupLayout(this.getContentPane());
getContentPane().setLayout(layout);
layout.setVerticalGroup(layout.createParallelGroup()
.addComponent(packMeButton)
.addComponent(text)
);
layout.setHorizontalGroup(layout.createSequentialGroup()
.addComponent(packMeButton)
.addComponent(text, DEFAULT_SIZE, 400, 400) //Lock the width to 400
);
pack();
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new TextSizeProblem();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
当运行它看起来像这样的程序: alt text http://lesc.se/stackoverflow/multiline_size_1.png
但我想的对话框看起来像这样(当你按包按钮): alt text http://lesc.se/stackoverflow/multiline_size_2.png
我猜测问题是布局管理器在将文本显示到屏幕之前未能确定正确的文本高度。我已经尝试过各种验证(),invalidate(),validateTree()等,但没有成功。
它呈现HTML标记吗?没有! – Soley 2015-02-21 07:22:10