JTable render Boolean as JToggleButton

889 views Asked by At

Hi I am able to render the Boolean column as a JToggleButton but if I keep the button pressed, I am seeing the checkbox instead of the button.

 TableColumnModel tcm = smartAlertsTable.getColumnModel();
 TableColumn tc = tcm.getColumn( Index of the boolean column);
 tc.setCellRenderer(new ActiveAlertRenderer());

where ActiveAlertRenderer is

public class ActiveAlertRenderer extends JToggleButton implements
    TableCellRenderer

{

public ActiveAlertRenderer()
{
    super();
}

public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column)
{

    boolean isActive = ((Boolean) value).booleanValue();
    if (isActive)
    {
        this.setText("Armed");
        this.setSelected(false);
        value = Boolean.TRUE;
    }
    else
    {
        this.setText("Triggered");
        this.setSelected(true);
        value = Boolean.FALSE;
    }
    return this;
}

}

How do I prevent the checkbox from appearing?

2

There are 2 answers

0
trainrobbery On

Try like this:

public class ActiveAlertRenderer extends DefaultTableRenderer {
    private JToggleButton toggleButton = new JToggleButton();

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

        if (column==INDEX_OF_TOGGLE_BUTTON_COLUMN) {
            boolean active = (Boolean) argValue;
            if (active) {
                toggleButton.setText("Armed");
            } else {
                toggleButton.setText("Triggered");
            }
            toggleButton.setSelected(active);
            return toggleButton; 
        }
        else {
            return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        }
    }

}

0
tenorsax On

JTable uses a checkbox as a default renderer and editor for boolean columns. You provided your own renderer but the editor remains default. This is the checkbox that you see when you edit the cell. You'd have to provide a custom editor (implementation of TableCellEditor) in a similar fashion you did the renderer. You can set it up using JTable.setDefaultEditor() or TableColumn.setCellRenderer.

See Concepts: Editors and Renderers in How to Use Tables tutorial for more details.