Hi I am having trouble with toggling a check box that is in a JList, I wish for when an item is clicked to have the check box tick, and if it is ticked again i want it to toggle to unticked. I want to have it possible to have multiple items to be ticked or unticked without the use of the ctrl or shift keys.
public class CustCellRenderer extends JCheckBox
implements ListCellRenderer
{
boolean selected = false;
void CustCellRenderer()
{
setOpaque(true);
setIconTextGap(12);
}
// allows a custom list cell rendering which will enable me to display an icon as well as filename
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{
JCheckBox checkBox = (JCheckBox)value;
if (isSelected)
{
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
if (!selected)
{
selected = true;
setSelected(selected);
}
else
{
selected = false;
setSelected(selected);
}
}
else
{
setBackground(list.getBackground());
setForeground(list.getForeground());
setSelected(selected);
}
setText(checkBox.getText());
return this;
}
}
Here is how I am trying to add data to the table, nothing appears for some reason, any thoughts?
public void addDirectoryLabelsToList()
{
// clears all the previous labels from the listModel to ensure only labels
// that refelect the current directory are shown
for (int x = 0; x < tableModel.getRowCount(); x++)
tableModel.removeRow(x);
// iterate through the dirLabels and add them to the listModel
for (JCheckBox j : dirLabels)
{
Vector<Object> obj = new Vector<>();
obj.add(Boolean.FALSE);
obj.add(j.getText());
tableModel.addRow(obj);
}
}
JList
allows custom renderers, but you'll need a custom editor, too. As an alternative, consider a JTable
having a Boolean.class
column, illustrated here.
Addendum: I have altered my question, please check.
I'm not sure where things are going awry, but I suspect your model's getColumnClass()
method does not return Boolean.class
for the relevant column. You might compare your implementation with this related example and post an sscce.