Swing/MaxWidthWrapOptionPane のバックアップ(No.4)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/MaxWidthWrapOptionPane へ行く。
- 1 (2016-04-07 (木) 22:16:40)
- 2 (2016-05-30 (月) 17:05:48)
- 3 (2016-06-30 (木) 18:54:29)
- 4 (2017-04-04 (火) 14:13:45)
- 5 (2017-04-07 (金) 13:51:51)
- 6 (2017-08-22 (火) 15:23:32)
- 7 (2018-09-06 (木) 11:03:02)
- 8 (2020-09-01 (火) 14:47:13)
- 9 (2022-03-13 (日) 06:19:08)
- 10 (2023-01-09 (月) 11:02:35)
- 11 (2025-01-03 (金) 08:57:02)
- 12 (2025-01-03 (金) 09:01:23)
- 13 (2025-01-03 (金) 09:02:38)
- 14 (2025-01-03 (金) 09:03:21)
- 15 (2025-01-03 (金) 09:04:02)
- category: swing
folder: MaxWidthWrapOptionPane
title: JOptionPaneに配置するJTextAreaの最大幅を指定してサイズ調整を行う
tags: [JTextArea, JOptionPane, JScrollPane]
author: aterai
pubdate: 2016-04-04T00:35:06+09:00
description: JOptionPaneに配置するJTextAreaの最大幅を指定し、テキストが複数行になってもその幅を超えず、スクロールバーも表示されない高さまで拡張されるよう設定します。
image:
概要
JOptionPane
に配置するJTextArea
の最大幅を指定し、テキストが複数行になってもその幅を超えず、スクロールバーも表示されない高さまで拡張されるよう設定します。
Screenshot

Advertisement
サンプルコード
private final JTextArea textArea = new JTextArea(1, 1) {
@Override public void updateUI() {
super.updateUI();
setLineWrap(true);
setWrapStyleWord(true);
setEditable(false);
setOpaque(false);
//setBorder(BorderFactory.createLineBorder(Color.RED));
setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
}
@Override public void setText(String t) {
super.setText(t);
try {
setColumns(50);
// http://docs.oracle.com/javase/8/docs/api/javax/swing/text/JTextComponent.html#modelToView-int-
// i.e. layout cannot be computed until the component has been sized.
// The component does not have to be visible or painted.
setSize(super.getPreferredSize()); //setSize: looks like ugly hack...
System.out.println(super.getPreferredSize());
Rectangle r = modelToView(t.length());
int rc = (int)(.5 + (r.y + r.height) / (float) getRowHeight());
setRows(rc);
System.out.format("Rows: %d%n", rc);
System.out.println(super.getPreferredSize());
if (rc == 1) {
setSize(getPreferredSize());
setColumns(1);
}
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
};
View in GitHub: Java, Kotlin解説
上記のサンプルでは、JTextArea#setText(...)
メソッドをオーバーライドして最大幅を固定したJTextArea
を作成し、これをJOptionPane#showMessageDialog(...)
で表示しています。
- 文字列が
JTextArea#setColumns(50)
で指定した最大幅を超えて複数行になる場合は、スクロールバーが表示されないようにJTextArea#setSize(super.getPreferredSize())
でJTextArea
の高さを調整 - 文字列が一行以内になる場合は、
JTextArea#setColumns(1)
で幅を上書きして、文字列の幅がそのサイズになるよう設定 NimbusLookAndFeel
やMotifLookAndFeel
で一行分のJTextArea
の幅設定ができない?JTextArea
の内余白が影響している?
JTextArea#setText(...)
時点でのサイズを設定し、ダイアログのリサイズは考慮しない
参考リンク
- java - Use width and max-width to wrap text in JOptionPane - Stack Overflow
- JTextComponent#modelToView(int) (Java Platform SE 8)