I am trying to create a JTable that allows for favoriting of items, but unfortunately the correct images do not show up on initial rendering, and then do not update properly until they lose focus in the cell.
To do this I've made column 1 a String and column 2 a boolean. I then overwrote the boolean renderer/editor as based on this question:
Java Swing, Trying to replace boolean check-box in a JTable with an image-icon checkbox
what I currently have:
public class FavoritableCellEditor extends AbstractCellEditor implements TableCellEditor {
private final FavoriteCheckBox cellEditor;
public FavoritableCellEditor() {
cellEditor = new FavoriteCheckBox();
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if (value instanceof Boolean) {
boolean selected = (boolean) value;
cellEditor.setSelected(selected);
}
return cellEditor;
}
@Override
public Object getCellEditorValue() {
return cellEditor.isSelected();
}
}
public class FavoritableCheckboxRenderer extends FavoriteCheckBox implements TableCellRenderer {
@Override
public void setSelected(boolean selected) {
super.setSelected(selected);
if (selected) {
setIcon(selIcon);
} else {
setIcon(unselIcon);
}
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof Boolean) {
boolean selected = (boolean) value;
setSelected(selected);
}
return this;
}
}
public class FavoriteCheckBox extends JCheckBox {
Icon selIcon;
Icon unselIcon;
public FavoriteCheckBox() {
try {
selIcon = new ImageIcon(ImageIO.read(getClass().getResource("/com/lmco/jsf/dqim/applications/TESTING/resources/baseline_star_black_18dp.png")));
unselIcon = new ImageIcon(ImageIO.read(getClass().getResource("/com/lmco/jsf/dqim/applications/TESTING/resources/baseline_star_border_black_18dp.png")));
} catch (IOException ex) {
Logger.getLogger(FavoriteCheckBox.class.getName()).log(Level.SEVERE, null, ex);
}
setHorizontalAlignment(CENTER);
}
@Override
public void setSelected(boolean selected) {
super.setSelected(selected);
if (selected) {
setIcon(selIcon);
} else {
setIcon(unselIcon);
}
revalidate();
repaint();
}
}
Demonstration:
I initially click where you see the check mark. Currently the correct images are not showing, but the default checkbox images.
I now click the bottom right corner to make that cell lose focus, it then paints itself filled with the correct image.
Finally I click where you see the check mark
An additional note: I've added in the revalidate() and repaint() myself, without it the behavior is largely the same except that it will never show the check marks again after initial rendering. It will still not update the image until focus is lost