Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

JList with Checkboxes

843805Mar 22 2007 — edited Mar 22 2007
For my application, I require a JList with each row containing a text label, and two check boxes which can be checked or unchecked in the list. I have written the code below to render list elements in this way, however the checkboxes cannot be checked in the list. Is there something else that I have to do to enable this?

Code:
public class NodeListCellRenderer implements ListCellRenderer {

	/**
	 * @see javax.swing.ListCellRenderer#getListCellRendererComponent(javax.swing.JList,
	 *      java.lang.Object, int, boolean, boolean)
	 */
	public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
			boolean cellHasFocus) {
		
		//Convert Value to node
		final Node n=(Node)value;
		
		//Create JPanel object to hold list element
		JPanel listElement=new JPanel();
		listElement.setLayout(new GridLayout(1,3));
		
		//Create Label to hold node name
		JLabel nodeName=new JLabel(n.toString());
		
		//Create checkbox to control trace
		final JCheckBox traceBox=new JCheckBox("Trace",n.isTraceEnabled());
		//Add Event Listener
		traceBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				n.setTrace(traceBox.isSelected());
			}
		});
				
		//Create Checkbox to control
		final JCheckBox failedBox=new JCheckBox("Failed",n.hasFailed());
		//Add Event Listener
		failedBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				n.setFailed(failedBox.isSelected());
			}			
		});
		
		//Colour All Components Grey if Selected
		if (isSelected) {
			nodeName.setBackground(Color.LIGHT_GRAY);
			failedBox.setBackground(Color.LIGHT_GRAY);
			traceBox.setBackground(Color.LIGHT_GRAY);
			listElement.setBackground(Color.LIGHT_GRAY);
		}
		
		//Build List Element
		listElement.add(nodeName);
		listElement.add(traceBox);
		listElement.add(failedBox);
		
		return listElement;
	}

}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 19 2007
Added on Mar 22 2007
4 comments
757 views