複数行のテキスト要素 (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);
}
});
}
}
プログラムを実行すると、次のようになります:
(ソース: lesc.se )
しかし、ダイアログを次のようにしたいと思います(パックボタンを押したときのように):(
ソース:lesc.se)
問題は、レイアウト マネージャーがテキストを画面に表示する前に適切な高さを判断できなかったことだと思います。さまざまな validate()、invalidate()、validateTree() などを試しましたが、成功しませんでした。