Question

how to set toggle button text value (depend on database) on jtable

Here is the code

private class CheckBoxCellEditor extends AbstractCellEditor implements

TableCellEditor, ItemListener {
    protected JToggleButton toggle;
    private String buttonValue;

    public CheckBoxCellEditor() {
        toggle = new JToggleButton("off");
        toggle.setHorizontalAlignment(SwingConstants.CENTER);           
        toggle.addItemListener(this);
    }

    public Component getTableCellEditorComponent(JTable table,
            Object value, boolean isSelected, int row, int column) {
        buttonValue = (value == null) ? "" : value.toString();
        return toggle;
    }

    public Object getCellEditorValue() {    
        // System.out.println( buttonValue);    
        return buttonValue;
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            toggle.setText("On!");
            System.out.println(buttonValue);
        } else {
            toggle.setText("Off");
            System.out.println(buttonValue);
        }    
    }
}

Here the image shows the toggle but it's not shows the text.

when i click the button the text shows then click next button the 1st one is not visible.

enter image description here

if you know the answer please share here.. with regards...

Was it helpful?

Solution

You've forgotten to set the value of the toggle button before returning it from the getTableCellEditorComponent

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


    buttonValue = (value == null) ? "" : value.toString();
    toggle.setText(buttonValue);


    return toggle;
}

To be honest, I'm curious with what's wrong with returning Boolean from getColumnClass in the table model for the Return column and simply let the default renderer and editor deal with it...

Also...you're ignore the button value when you return it from the editor...

public Object getCellEditorValue() {

    // System.out.println( buttonValue);

    return buttonValue;
}

Frankly, probably better to use toggle.getText()...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top