Swing/CellEditorBorder のバックアップの現在との差分(No.2)
CellEditorのBorderを変更
編集者:Terai Atsuhiro~
作成日:2005-08-22
更新日:2023-11-16 (木) 14:54:55
概要
Border
を変更したJTextField
を、JTable
のデフォルトセルエディタとして設定します。
Screenshot
Advertisement
概要
JTableのCellEditorにBorderを設定します。サンプルコード
解説
上記のサンプルでは、LineBorder
を設定したJTextField
を使用するDefaultCellEditor
を作成し、JTable#setDefaultEditor(...)
メソッドでObject
クラスのデフォルトセルエディタとして設定しています。
サンプルコード
JTextField tf = new JTextField(); tf.setBorder(BorderFactory.createLineBorder(Color.red, 2)); table.setDefaultEditor(Object.class, new DefaultCellEditor(tf)); JTextField tf2 = new JTextField(); tf2.setBorder(BorderFactory.createLineBorder(Color.green, 2)); tf2.setHorizontalAlignment(JTextField.RIGHT); table.setDefaultEditor(Integer.class, new DefaultCellEditor(tf2));
-
JTable#setDefaultEditor(...)
を使用せずにJTable#prepareEditor(...)
をオーバーライドしてセルエディタとして使用するコンポーネントの背景色やBorder
を変更する方法もある
- サンプルを起動
- jarファイル
- ソース
#spanend #spanadd JTable table = new JTable(model) { #spanend @Override public Component prepareEditor( TableCellEditor editor, int row, int column) { Component c = super.prepareEditor(editor, row, column); if (c instanceof JCheckBox) { JCheckBox b = (JCheckBox) c; b.setBorderPainted(true); b.setBackground(getSelectionBackground()); } else if (c instanceof JComponent && convertColumnIndexToModel(column) == 1) { ((JComponent) c).setBorder( BorderFactory.createLineBorder(Color.GREEN, 2)); } return c; } #spanadd }; #spanend #spanadd
解説
サンプルでは、DefaultTableModel#getColumnClassメソッドをオーバーライドして0列目はInteger.classを返すようにしています。Integer.classの場合はBorderが緑、それ以外の場合(Object.class)は赤で描画するようなデフォルトエディタをそれぞれ指定しています。参考リンク
以下のようにJTable#getColumnClassをオーバーライドしても同様です。table = new JTable(sorter) { public Class getColumnClass(int column) { if(column==0) { return Integer.class; } return Object.class; } };デフォルトレンダラーの設定にも、getColumnClassが返すクラスが影響するので、それぞれレンダラーを設定する必要があります。
TestRenderer tr = new TestRenderer(); table.setDefaultRenderer(Object.class, tr); table.setDefaultRenderer(Integer.class, tr);
コメント
- DefaultTableModel#getColumnClassとJTable#getColumnClassで動作が異なると勘違い*1して解説していたのを修正しました。 -- terai
- 0列目を実際に編集してソートするとClassCastExceptionが発生するバグがあります。 -- terai