# JTable - JCheckbox und Renderer



## dmatdh (2. Apr 2009)

Hey,
ich sitze nun seit guten 4 Tagen an dem Problem und komme einfach nicht weiter!
Ich habe eine Kontaktdatenbank und möchte, falls eine Bedingung auftritt (in einer Datenbank ein bestimmter Wert über 0 ist) die ganze Spalte farblich makieren! 
Da beginnt schon das Problem. Für die farbliche Makierung benötige ich einen eigenen Renderer, welcher geschrieben wurde und soweit funktioniert...
Leider überschreibt mein Renderer den DefaultRenderer und somit sind bei boolean true/false keine JCheckBox mehr vorhanden.
Nach langen suchen habe ich eine Lösung dazu gefunden aber nun stehe ich vor dem Problem, dass die JCheckBox kein Häkchen bekomtm sondern ein JTextField - zumindest zum Editieren!)
Brauche Hilfe, komme nicht mehr weiter!
Ich poste einfach mal den Code:

[HIGHLIGHT="Java"]package main;

import configuration.Mysql;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeCellEditor;

/**
 * @author dmat
 */

public class Tabelle extends JPanel {

  protected JTable m_table;
  protected KontaktdatenTabelle m_data;
  public JScrollPane ps = new JScrollPane();

  public Tabelle() {
      setSize(600, 300);

    m_data = new KontaktdatenTabelle();

    m_table = new JTable();
    m_table.setAutoCreateColumnsFromModel(false);
    m_table.setModel(m_data);

    for (int k = 0; k < KontaktdatenTabelle.m_columns.length; k++) {
      DefaultTableCellRenderer renderer = new ColoredTableCellRenderer();
      renderer.setHorizontalAlignment(KontaktdatenTabelle.m_columns[k].m_alignment);
      TableColumn column = new TableColumn(k,KontaktdatenTabelle.m_columns[k].m_width, renderer, null);
      m_table.addColumn(column);
    }

    m_table.setDefaultRenderer(Boolean.class, new ColoredTableCellRenderer());

    JTableHeader header = m_table.getTableHeader();
    header.setUpdateTableInRealTime(true);
    header.addMouseListener(m_data.new ColumnListener(m_table));
    header.setReorderingAllowed(true);

    m_table.getColumnModel().addColumnModelListener( m_data.new ColumnMovementListener() );


    ps.getViewport().add(m_table);
    setLayout(new BorderLayout());
    add(ps, BorderLayout.CENTER);

    setVisible(true);
  }

  public JTable getTable() {
      return m_table;
  }

  public static void main( String[] args ) {
      new Tabelle();
  }

  class ColumnKeeper implements ActionListener
  {
    protected TableColumn m_column;
    protected ColumnData  m_colData;

    public ColumnKeeper(TableColumn column, ColumnData  colData) {
      m_column = column;
      m_colData = colData;
    }

    public void actionPerformed(ActionEvent e) {
      JCheckBoxMenuItem item = (JCheckBoxMenuItem)e.getSource();
      TableColumnModel model = m_table.getColumnModel();
      if (item.isSelected()) {
        model.addColumn(m_column);
      }
      else {
        model.removeColumn(m_column);
      }
      m_table.tableChanged(new TableModelEvent(m_data));
      m_table.repaint();
    }
  }
}

interface TreeCellEditor
extends javax.swing.CellEditor {

}

class ColoredTableCellRenderer
        extends DefaultTableCellRenderer
{
    DefaultTreeCellRenderer d = new DefaultTreeCellRenderer();
    DefaultTreeCellEditor e = new DefaultTreeCellEditor( new JTree(), d );
  public void setValue(Object value)
  {
    if (value instanceof ColorData) {
      ColorData cvalue = (ColorData)value;
      setForeground(cvalue.m_color);
      setText(cvalue.m_data.toString());
    }
    else if (value instanceof IconData) {
      IconData ivalue = (IconData)value;
      setIcon(ivalue.m_icon);
      setText(ivalue.m_data.toString());
    }
    else
      super.setValue(value);
  }


   public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row,int column) {
        if (value instanceof Boolean) {
            boolean enabled = ((Boolean) value).booleanValue();
            final JCheckBox box = new JCheckBox();
            box.setHorizontalAlignment(SwingConstants.CENTER);
            box.setSelected(enabled);


            if (enabled) {
                box.setBackground(Color.GREEN);
            }
            return box;
        }

        return super.getTableCellRendererComponent(table,
                value, isSelected, hasFocus, row, column);
   }
}

class SmartLong
{
  protected static NumberFormat FORMAT;
  static {
    FORMAT = NumberFormat.getInstance();
    FORMAT.setGroupingUsed(true);
  }

  public long m_value;

  public SmartLong(long value) { m_value = value; }

  public long longValue() { return m_value; }

  public String toString() { return FORMAT.format(m_value); }
}


class ColorData {
  public Color  m_color;
  public Object m_data;
  public static Color GREEN = new Color(0, 128, 0);
  public static Color RED = Color.red;

  public ColorData(Double data) {
    m_color = data.doubleValue() > 0 ? GREEN : RED;
    m_data  = data;
  }

  public String toString() {
    return m_data.toString();
  }
}

class IconData {
  public ImageIcon  m_icon;
  public Object m_data;

  public IconData(ImageIcon icon, Object data) {
    m_icon = icon;
    m_data = data;
  }

  public String toString() {
    return m_data.toString();
  }
}

class Kontaktdaten {

   public String my_id;
   public boolean my_bool;
   public String my_vorname;
   public String my_nachname;
   public String my_titel;
   public String my_firmenname;
   public String my_strasse;
   public String my_wohnort;
   public String my_plz;
   public String my_bundesland;
   public String my_telefonp;
   public String my_telefong;
   public String my_email;
   public String my_datum;
   public ColorData my_makiert;


  public Kontaktdaten(String id, boolean bool, String vorname, String nachname, String titel, String firmenname, String strasse, String wohnort, String plz, String bundesland, String telefonp, String telefong, String email, String datum,double makiert) {
    my_id=id; my_bool=bool; my_vorname=vorname;my_nachname=nachname;my_titel=titel;my_firmenname=firmenname;
    my_strasse=strasse;my_wohnort=wohnort;my_plz=plz;my_bundesland=bundesland;my_telefonp=telefonp;
    my_telefong=telefong;my_email=email; my_datum=datum;
    my_makiert= new ColorData( makiert );
  }

}

class ColumnData {
  public String  m_title;
  public int     m_width;
  public int     m_alignment;

  public ColumnData(String title, int width, int alignment) {
    m_title = title;
    m_width = width;
    m_alignment = alignment;
  }
}

class KontaktdatenTabelle extends AbstractTableModel {
  static final public ColumnData m_columns[] = {
      new ColumnData("ID", 1, JLabel.CENTER),
      new ColumnData("Select", 2, JLabel.CENTER),
      new ColumnData("Vorname", 40, JLabel.CENTER),
      new ColumnData("Nachname", 45, JLabel.CENTER),
      new ColumnData("Titel", 75, JLabel.CENTER),
      new ColumnData("Firmenname", 125, JLabel.CENTER),
      new ColumnData("Strasse", 100, JLabel.CENTER),
      new ColumnData("Wohnort", 45, JLabel.CENTER),
      new ColumnData("PLZ", 28, JLabel.CENTER),
      new ColumnData("Bundesland", 78, JLabel.CENTER),
      new ColumnData("Telefon (Privat)", 60, JLabel.CENTER),
      new ColumnData("Telefon (Geschäft)", 80, JLabel.CENTER),
      new ColumnData("E-Mail", 70, JLabel.CENTER),
      new ColumnData("Datum", 8, JLabel.CENTER),
      new ColumnData("Sendungen", 10, JLabel.CENTER )
  };

   boolean[] canEdit = new boolean [] {
        false,true,false,false,false,false,false,false,false,false,false,false,false,false,false
  };

  public KontaktdatenTabelle() {
    m_vector = new Vector();
    setDefaultData();
  }

  protected SimpleDateFormat m_frm;
  protected Vector m_vector;
  protected int m_columnsCount = m_columns.length;

  protected int m_sortCol = 0;
  protected boolean m_sortAsc = true;

  protected int m_result = 0;

  public void setDefaultData() {
    m_vector.removeAllElements();
    Mysql s = new Mysql();
    Integer array_ids[] = s.gibIds();
    for(Integer i = 0; i < array_ids.length; i++) {
        m_vector.addElement(new Kontaktdaten(array_ids_.toString(), Boolean.FALSE , s.gibVorname(array_ids.toString()), s.gibNachname(array_ids.toString()), s.gibTitel(array_ids.toString()), s.gibFirmenname(array_ids.toString()), s.gibStrasse(array_ids.toString()),s.gibWohnort(array_ids.toString()),s.gibPLZ(array_ids.toString()), s.gibBundesland(array_ids.toString()), s.gibTelefonPrivat(array_ids.toString()), s.gibTelefonPrivat(array_ids.toString()), s.gibEmail(array_ids.toString()), "" ,new Double( Double.valueOf(s.gibMarkiert( array_ids.toString()))) ));
    }

    Collections.sort(m_vector, new KontaktVergleicher(m_sortCol, m_sortAsc));
  }

  public int getRowCount() {
    return m_vector==null ? 0 : m_vector.size();
  }

  public int getColumnCount() {
    return m_columnsCount;
  }

  public String getColumnName(int column) {
    String str = m_columns[column].m_title;
    if (column==m_sortCol)
      str += m_sortAsc ? ">>" : "<<";
    return str;
  }

  public Class getColumnClass(int columnIndex) {
     return (columnIndex == 0) ? Boolean.class : String.class;
  }

  public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit [columnIndex];
  }



  public Object getValueAt(int nRow, int nCol) {
    if (nRow < 0 || nRow >= getRowCount())
      return "";
    Kontaktdaten row = (Kontaktdaten) m_vector.elementAt(nRow);
    switch (nCol) {
        case 0:
            return row.my_id;
        case 1:
             return row.my_bool;
        case 2:
            return row.my_vorname;
        case 3:
               return row.my_nachname;
        case 4:
             return row.my_titel;
        case 5:
             return row.my_firmenname;
        case 6:
            return row.my_strasse;
        case 7:
            return row.my_wohnort;
        case 8:
            return row.my_plz;
        case 9:
            return row.my_bundesland;
        case 10:
            return row.my_telefonp;
        case 11:
            return row.my_telefong;
        case 12:
            return row.my_email;
        case 13:
            return row.my_datum;
        case 14:
            return row.my_makiert;
    }
    return "";
  }

  class ColumnListener extends MouseAdapter
  {
    protected JTable m_table;

    public ColumnListener(JTable table) {
      m_table = table;
    }

    public void mouseClicked(MouseEvent e) {
      TableColumnModel colModel = m_table.getColumnModel();
      int columnModelIndex = colModel.getColumnIndexAtX(e.getX());
      int modelIndex = colModel.getColumn(columnModelIndex).getModelIndex();

      if (modelIndex < 0)
        return;
      if (m_sortCol==modelIndex)
        m_sortAsc = !m_sortAsc;
      else
        m_sortCol = modelIndex;

      for (int i=0; i < m_columnsCount; i++) { //NEW
        TableColumn column = colModel.getColumn(i);
        column.setHeaderValue(getColumnName(column.getModelIndex()));
      }
      m_table.getTableHeader().repaint();

      Collections.sort(m_vector, new
        KontaktVergleicher(modelIndex, m_sortAsc));
      m_table.tableChanged(
        new TableModelEvent(KontaktdatenTabelle.this));
      m_table.repaint();
    }
  }

  class ColumnMovementListener implements TableColumnModelListener
  {
    public void columnAdded(TableColumnModelEvent e) {
      m_columnsCount++;
    }

    public void columnRemoved(TableColumnModelEvent e) {
      m_columnsCount--;
      if (m_sortCol >= e.getFromIndex())
        m_sortCol = 0;
    }

    public void columnMarginChanged(ChangeEvent e) {}
    public void columnMoved(TableColumnModelEvent e) {}
    public void columnSelectionChanged(ListSelectionEvent e) {}
  }
}

class KontaktVergleicher implements Comparator
{
  protected int     m_sortCol;
  protected boolean m_sortAsc;

  public KontaktVergleicher(int sortCol, boolean sortAsc) {
    m_sortCol = sortCol;
    m_sortAsc = sortAsc;
  }

  public int compare(Object o1, Object o2) {
    if(!(o1 instanceof Kontaktdaten) || !(o2 instanceof Kontaktdaten))
      return 0;
    Kontaktdaten s1 = (Kontaktdaten)o1;
    Kontaktdaten s2 = (Kontaktdaten)o2;
    int result = 0;
    double d1, d2;
    switch (m_sortCol) {
      case 0:    // symbol
        String str1 = (String)s1.my_id;
        String str2 = (String)s2.my_id;
        result = str1.compareTo(str2);
        break;
      case 1:    // name
        result = s1.my_vorname.compareTo(s2.my_vorname);
        break;
      case 2:    // nachname
        result = s1.my_nachname.compareTo(s2.my_nachname);
        break;
      case 3: // titel
        result = s1.my_titel.compareTo(s2.my_titel);
        break;
      case 4:
        result = s1.my_firmenname.compareTo(s2.my_firmenname);
        break;
      case 5:
        result = s1.my_strasse.compareTo(s2.my_strasse);
        break;
      case 6:
        result = s1.my_wohnort.compareTo(s2.my_wohnort);
        break;
      case 7:
        result = s1.my_wohnort.compareTo(s2.my_wohnort);
        break;
      case 8:
        d1 = Double.valueOf(s1.my_plz).doubleValue();
        d2 = Double.valueOf(s2.my_plz).doubleValue();
        result = d1<d2 ? -1 : (d1>d2 ? 1 : 0);
        break;
      case 9:
        result = s1.my_bundesland.compareTo(s2.my_bundesland);
        break;
      case 10:
        result = s1.my_telefonp.compareTo(s2.my_telefonp);
        break;
      case 11:
        result = s1.my_telefong.compareTo(s2.my_telefong);
        break;
      case 12:
        result = s1.my_email.compareTo(s2.my_email);
        break;
      case 13:

      case 14:
        d1 = ((Double)s1.my_makiert.m_data).doubleValue();
        d2 = ((Double)s2.my_makiert.m_data).doubleValue();
        result = d1<d2 ? -1 : (d1>d2 ? 1 : 0);
        break;
    }

    if (!m_sortAsc)
      result = -result;
    return result;
  }

  public boolean equals(Object obj) {
    if (obj instanceof KontaktVergleicher) {
      KontaktVergleicher compObj = (KontaktVergleicher)obj;
      return (compObj.m_sortCol==m_sortCol) &&
        (compObj.m_sortAsc==m_sortAsc);
    }
    return false;
  }
}[/HIGHLIGHT]

hier ein Pastebinlink: pastebin - collaborative debugging tool

Danke!_


----------



## Marco13 (5. Apr 2009)

Viel unformatierter Code und Ansätze, die man wohl als "yakshaving" bezeichnet .... wenn es NUR darum geht, den CheckBoxes eine andere Hintergrundfarbe zu geben, geht das evtl. einfacher ... ohne dass man eigene Renderer und Editoren schreibt (was ziemlich frickelig sein kann)...

Ich habe mal in der "TableDemo.java" von How to Use Tables (The Java™ Tutorials > Creating a GUI with JFC/Swing > Using Swing Components) das Erstellen der Table geändert in

```
JTable table = new JTable(new MyTableModel())
        {
            public TableCellRenderer getCellRenderer(int row, int column)
            {
                final TableCellRenderer r = super.getCellRenderer(row,column);
                if (column == 4)
                {
                    return new TableCellRenderer()
                    {
                        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
                        {
                            Component c = r.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                            c.setBackground(Color.RED);
                            return c;
                        }
                    };
                }
                return r;
            }
        };
```
Und damit werden die Checkboxes rot hinterlegt. Vielleicht kannst du einen ähnlichen Ansatz ja bei dir verwenden...


----------



## André Uhres (6. Apr 2009)

Oder ohne eigenen Renderer:

```
m_table = new JTable() {
    @Override
    public Component prepareRenderer(final TableCellRenderer renderer,
            final int row, final int column) {
        Component c = super.prepareRenderer(renderer, row, column);
        adaptColors(c, convertRowIndexToModel(row), convertColumnIndexToModel(column));
        return c;
    }
    private void adaptColors(final Component c, final int row, final int column) {
        c.setBackground(getBackground());
        c.setForeground(getForeground());
        Object value = dataModel.getValueAt(row, column);
        if (column == 1) {// 1 = Select
            if (((Boolean) value)) {
                c.setBackground(Color.GREEN);
            }
        }
    }
};
```


----------

