何種類かのテキスト要素(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私はこのコードを持っています
私は、レイアウトマネージャが画面に表示する前にテキストの適切な高さを判断できていないことが問題であると推測しています。私は様々なvalidate()、invalidate()、validateTree()などを試みましたが、成功しませんでした。
HTMLタグをレンダリングしますか?いいえ! – Soley