• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JComboBoxなどの幅をカラム数で指定
#navi(../)
*JComboBoxなどの幅をカラム数で指定 [#ve8ef0dc]
Posted by [[terai]] at 2006-12-18
---
title: JComboBoxなどの幅をカラム数で指定
tags: [JTextField, JPasswordField, JSpinner, JComboBox]
author: aterai
pubdate: 2006-12-18T16:11:14+09:00
---
* 概要 [#ve8ef0dc]
`JTextField`,`JPasswordField`,`JSpinner`,`JComboBox`の幅をカラム数で指定して比較しています。

#contents
#download(https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTS72PP0tI/AAAAAAAAAjk/RRG_w2fJBtA/s800/SetColumns.png)

**概要 [#hb1df07a]
JTextField,JPasswordField,JSpinner,JComboBox の幅をカラム数で指定して比較しています。

-&jnlp;
-&jar;
-&zip;

#screenshot

**サンプルコード [#ib603a1f]
#code{{
* サンプルコード [#ib603a1f]
#code(link){{
JTextField field      = new JTextField(20);
JPasswordField passwd = new JPasswordField(20);
JSpinner.DefaultEditor e = (JSpinner.DefaultEditor)spinner.getEditor();
e.getTextField().setColumns(20);
combo1.setEditable(true);
Component c = combo1.getEditor().getEditorComponent();
if(c instanceof JTextField) ((JTextField)c).setColumns(20);
}}

**解説 [#fd934c68]
上記のサンプルでは、要素が空のJComboBoxなどのカラム幅を同じにして((下二つはdefaultのまま))、以下のような順番で並べています。
+JTextField [setColumns(20)]
+JPasswordField [setColumns(20)]
+JSpinner [setColumns(20)]
+JComboBox [setEditable(true), setColumns(20)]
+JComboBox [setEditable(true), default]
+JComboBox [setEditable(false), default]
* 解説 [#fd934c68]
上記のサンプルでは、要素が空の`JComboBox`などのカラム幅を同じにして(下二つは`default`のまま)、以下のような順番で並べています。
+ `JTextField` [`setColumns(20)`]
+ `JPasswordField` [`setColumns(20)`]
+ `JSpinner` [`setColumns(20)`]
+ `JComboBox` [`setEditable(true)`, `setColumns(20)`]
+ `JComboBox` [`setEditable(true)`, `default`]
+ `JComboBox` [`setEditable(false)`, `default`]

スクリーンショットは、左(上)が 1.6.0(Java SE 6) で、右(下)が、1.5.0_10 で実行したものになっています(どちらもWindows L&F)。1.6.0 ではきれいに揃っていますが、1.5.0_10 などでは幅も高さも余白もガタガタ((1.5では左の内余白もJTextFieldは広すぎ、JComboBoxなどは狭すぎるなどバラバラ))なので、レイアウトマネージャーで工夫するか、setPreferredSize(Dimension)を使って幅を揃える方がよさそうです([[JButtonなどの高さを変更せずに幅を指定>Swing/ButtonWidth]])。
スクリーンショットは、左が`JDK 1.6.0`、右が、`JDK 1.5.0_10`で実行したものになっています(どちらも`WindowsLookAndFeel`)。`1.6.0`ではきれいに揃っていますが、`1.5.0_10`などでは幅も高さも余白もガタガタ(左の内余白も`JTextField`は広すぎ、`JComboBox`などは狭すぎるなどバラバラ)なので、レイアウトマネージャーで工夫するか、`setPreferredSize(Dimension)`を使って幅を揃える方がよさそうです([[JButtonなどの高さを変更せずに幅を指定>Swing/ButtonWidth]])。

**参考リンク [#oe03e66c]
-[[JButtonなどの高さを変更せずに幅を指定>Swing/ButtonWidth]]
* 参考リンク [#oe03e66c]
- [[JButtonなどの高さを変更せずに幅を指定>Swing/ButtonWidth]]

**コメント [#w970c125]
* コメント [#w970c125]
#comment
#comment