
can we add checkox to List

Hi Friend,
Try the following code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
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;
}
}
Thanks
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.