TITLE:CellEditorのBorderを変更
#navi(../)
*CellEditorのBorderを変更 [#ia1fb931]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2005-08-22~
更新日:&lastmod;

#contents

**概要 [#j484283d]
JTableのCellEditorにBorderを設定します。

#screenshot

**サンプルコード [#t48217b5]
#code{{
 JTextField tf1 = new JTextField();
 tf1.setBorder(BorderFactory.createLineBorder(Color.red, 2));
 table.setDefaultEditor(Object.class, new DefaultCellEditor(tf1));
 
 JTextField tf2 = new JTextField();
 tf2.setHorizontalAlignment(JTextField.RIGHT);
 tf2.setBorder(BorderFactory.createLineBorder(Color.green, 2));
 table.setDefaultEditor(Integer.class, new DefaultCellEditor(tf2) {
   public boolean stopCellEditing() {
     Object o = getCellEditorValue();
     return (o==null)?false:super.stopCellEditing();
   }
   public Object getCellEditorValue() {
     Object o = super.getCellEditorValue();
     Integer iv;
     try{
       iv = Integer.valueOf(o.toString());
     }catch(NumberFormatException nfe) {
       iv = null;
     }
     return iv;
   }
 });
}}
-&jnlp;
-&jar;
-&zip;

**解説 [#q9485122]
サンプルでは、DefaultTableModel#getColumnClassメソッドをオーバーライドして0列目はInteger.classを返すようにしています。Integer.classの場合はBorderが緑、それ以外の場合(Object.class)は赤で描画するようなデフォルトエディタをそれぞれ指定しています。

以下のようにJTable#getColumnClassをオーバーライドしても同様です。
#code{{
 table = new JTable(sorter) {
   public Class getColumnClass(int column) {
     if(column==0) {
       return Integer.class;
     }
     return Object.class;
   }
 };
}}

デフォルトレンダラーの設定にも、getColumnClassが返すクラスが影響するので、それぞれレンダラーを設定する必要があります。
#code{{
 TestRenderer tr = new TestRenderer();
 table.setDefaultRenderer(Object.class,  tr);
 table.setDefaultRenderer(Integer.class, tr);
}}

//**参考リンク
**コメント [#q0b2f0c8]
- DefaultTableModel#getColumnClassとJTable#getColumnClassで動作が異なると勘違い((コンパイルし忘れていたみたいです))して解説していたのを修正しました。 -- [[terai]] &new{2005-08-22 (月) 16:53:30};
- 0列目を実際に編集してソートするとClassCastExceptionが発生するバグがあります。 -- [[terai]] &new{2005-08-22 (月) 17:07:47};
-- 修正するのを綺麗サッパリ忘れていました…。修正しました。 -- [[terai]] &new{2007-02-15 (木) 16:34:10};

#comment