JCheckBox的问题检查了Java JList中的切换逻辑 [英] Trouble with JCheckBox checked toggle logic in a JList in Java
问题描述
我在切换JList中的复选框时遇到了麻烦,我希望单击某个项目以使复选框打勾,如果再次打勾,我希望将其切换为未打勾.我希望有可能在不使用ctrl或shift键的情况下勾选或取消勾选多个项目.
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
允许自定义渲染器,但您也需要自定义编辑器.作为替代方案,考虑具有Boolean.class
列的JTable
,在此处所示.
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.
附录:我已更改我的问题,请检查.
我不确定哪里出错了,但是我怀疑您模型的getColumnClass()
方法没有为相关列返回Boolean.class
.您可以将实现与与此相关的示例进行比较,然后发布
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.
这篇关于JCheckBox的问题检查了Java JList中的切换逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!