如何渲染JTable中的复选框?

时间:2010-11-11 13:19:58

标签: java swing checkbox jtable

这是我的代码,用于呈现JTable并更改行的颜色,但它不会在第6列中显示复选框,只显示字符串(true,false)。

您能提供解决方案吗?

提前致谢。

    public class JLabelRenderer extends JLabel implements TableCellRenderer
{
  private MyJTable myTable;
  /**
   * Creates a Custom JLabel Cell Renderer
   * @param t your JTable implmentation that holds the Hashtable to inquire for
   * rows and colors to paint.
   */
  public JLabelRenderer(MyJTable t)
  {
    this.myTable = t;
  }

  /**
   * Returns the component used for drawing the cell.  This method is
   * used to configure the renderer appropriately before drawing.
   * see TableCellRenderer.getTableCellRendererComponent(...); for more comments on the method
   */
  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
  {
    setOpaque(true); //JLabel isn't opaque by default

    setText(value.toString());
    setFont(myTable.getFont());

    if(!isSelected)//if the row is not selected then use the custom color
    setBackground(myTable.getRowToPaint(row));
    else //if the row is selected use the default selection color
    setBackground(myTable.getSelectionBackground());

    //Foreground could be changed using another Hashtable...
    setForeground(myTable.getForeground());

    // Since the renderer is a component, return itself
    return this;
  }

  // The following methods override the defaults for performance reasons
  public void validate() {}
  public void revalidate() {}
  protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {}
  public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {}
}

这是表格:

import javax.swing.JTable;    
import javax.swing.table.*;
import java.util.Hashtable;
import java.awt.Color;

public class MyJTable extends JTable
{
  Hashtable rowsToPaint = new Hashtable(1);

  /**
   * Default Constructor
   */
  public MyJTable()
  {
    super();
  }

  /**
   * Set the TableModel and then render each column with a custom cell renderer
   * @param tm TableModel
   */
  public void setModel(TableModel tm)
  {
    super.setModel(tm);
    renderColumns(new JLabelRenderer(this));
  }

  /**
   * Add a new entry indicating:
   * @param row the row to paint - the first row = 0;
   * @param bgColor background color
   */
  public void addRowToPaint(int row, Color bgColor)
  {
    rowsToPaint.put(new Integer(row), bgColor);
    this.repaint();// you need to repaint the table for each you put in the hashtable.
  }

  /**
   * Returns the user selected BG Color or default BG Color.
   * @param row the row to paint
   * @return Color BG Color selected by the user for the row
   */
  public Color getRowToPaint(int row)
  {
    Color bgColor = (Color)rowsToPaint.get(new Integer(row));
    return (bgColor != null)?bgColor:getBackground();
  }

  /**
   * Render all columns with the specified cell renderer
   * @param cellRender TableCellRenderer
   */
  public  void renderColumns(TableCellRenderer cellRender)
  {
    for(int i=0; i<this.getModel().getColumnCount(); i++)
    {
      renderColumn(this.getColumnModel().getColumn(i), cellRender);
    }
  }

  /**
   * Render a TableColumn with the sepecified Cell Renderer
   * @param col TableColumn
   * @param cellRender TableCellRenderer
   */
  public void renderColumn(TableColumn col, TableCellRenderer cellRender)
  {
    try{
          col.setCellRenderer(cellRender);
        }catch(Exception e){System.err.println("Error rendering column: [HeaderValue]: "+col.getHeaderValue().toString()+" [Identifier]: "+col.getIdentifier().toString());}
  }
}

这是我的屏幕 alt text

4 个答案:

答案 0 :(得分:7)

此问题的最佳解决方案是实施您自己的TableModel(通常通过子类AbstractTableModel)并实施getColumnClass(int)方法以返回列的Boolean.class您希望呈现为JCheckBox

由于TableCellRenderer默认使用的DefaultTableCellRenderer会自动将JTable列呈现为Boolean,因此无需实施您自己的JCheckbox。{ / p>

答案 1 :(得分:3)

正如您可能知道的那样,JTable会将布尔值作为复选框呈现给您。我认为您的问题是,开箱即用,您无法根据数据中的特定条件为每行设置自定义背景颜色。您可以为TableCellRenderer列创建新的boolean

您有几个选择:

  1. 您可以在当前渲染器中放置一个测试,以确定传入的value是否为布尔值,如果是,则配置要返回的JCheckbox实例。这可能会影响您的需求,但您需要小心,因为您的渲染器经常被调用,如果您创建一次性JCheckbox es,则可能会导致大量的流失。

  2. 或者,您可以创建一个扩展TableCellRenderer的新JCheckbox(正如您当前扩展JLabel一样。您可能希望重构当前的着色逻辑,以便它可以在两个渲染器之间共享。最后,您可能希望将此渲染器与列关联。您可以通过将其设置为表格中的默认渲染器来执行此操作,以获取特定ClassmyTable.setDefaultRenderer(Class, TableCellRenderer) ),或将其设置为特定列(myTable.getColumnModel().getColumn(int).setCellRenderer(TableCellRenderer)

  3. 的渲染器

答案 2 :(得分:3)

谢谢 akf 我解决了它:

添加课程:

public class CheckBoxRenderer extends JCheckBox implements TableCellRenderer {

          CheckBoxRenderer() {
            setHorizontalAlignment(JLabel.CENTER);
          }

          public Component getTableCellRendererComponent(JTable table, Object value,
              boolean isSelected, boolean hasFocus, int row, int column) {
            if (isSelected) {
              setForeground(table.getSelectionForeground());
              //super.setBackground(table.getSelectionBackground());
              setBackground(table.getSelectionBackground());
            } else {
              setForeground(table.getForeground());
              setBackground(table.getBackground());
            }
            setSelected((value != null && ((Boolean) value).booleanValue()));
            return this;
          }
}

编辑Mytable的构造函数:

 public MyJTable(DefaultTableModel md)
  {
    super(md);
    CheckBoxRenderer checkBoxRenderer = new CheckBoxRenderer();
    this.getColumnModel().getColumn(6).setCellRenderer(checkBoxRenderer);
  }

答案 3 :(得分:1)

我觉得使用Table Row Rendering方法更容易做到这一点。它可以在不为每列创建单独的渲染器的情况下工作。