Requesting help on tweeking a JCheckBox JList
Hi, I have a problem with a JCheckBox JList I found on the web. I don't normally ask for help since I found that any question I seem to have usually gets solved by some intense Google searching. but here is my dilemma:
I was searching for a JCheckBox JList that I could implement into my script, I found one ont he web that someone had produced. It works good I just need something tweeked on it.
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class CheckBoxInList
{
public static void main(String args[])
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JList list = new JList(new CheckListItem[] {new CheckListItem("1"), new CheckListItem("2"), new CheckListItem("3"), new CheckListItem("4"), new CheckListItem("5")});
list.setCellRenderer(new CheckListRenderer());
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent event)
{
JList list = (JList) event.getSource();
int index = list.locationToIndex(event.getPoint());
CheckListItem item = (CheckListItem)
list.getModel().getElementAt(index);
item.setSelected(! item.isSelected());
list.repaint(list.getCellBounds(index, index));
}
});
frame.getContentPane().add(new JScrollPane(list));
frame.pack();
frame.setVisible(true);
}
}
class CheckListItem
{
private String label;
private boolean isSelected = false;
public CheckListItem(String label)
{
this.label = label;
}
public boolean isSelected()
{
return isSelected;
}
public void setSelected(boolean isSelected)
{
this.isSelected = isSelected;
}
public String toString()
{
return label;
}
}
class CheckListRenderer extends JCheckBox implements ListCellRenderer
{
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean hasFocus)
{
setEnabled(list.isEnabled());
setSelected(((CheckListItem)value).isSelected());
setFont(list.getFont());
setBackground(list.getBackground());
setForeground(list.getForeground());
setText(value.toString());
return this;
}
}
That is the code, now what I am currently trying to do is instead of adding JCheckBoxes as so: Code:
new CheckListItem("1")
I was hoping to do something like this:
Code:
int arrayAmount = 20;
String textArray[] = {"Text", "More Text", "Even More Text", "Etc."};
JCheckBox jcheckboxArray[] = new JCheckBox[arrayAmount];
JList list = new JList(jcheckboxArray);
And set values later by doing this:
Code:
for (int i = 0; i < arrayAmount; i ++)
{
jcheckboxArray[i] = new JCheckBox(textArray[i]);
}
Its just that my textArray[i] is forever changing in size and wording. Any help is appreciated since this portion is out of my league. But I would appreciate an explanation if not asking to much so I could further learn from this and possibly Render Cells efficiently myself someday.