interacting with source from an event

I have a question about swing events. In the actionPerformed() or itemStateChanged() methods, is it possible to get the source or the event, and interact with it? What I’m trying to do here is just limit how many boxes can be checked. If the user selects more than six boxes, I want that 7th box to automatically uncheck, however, I’m not sure how to refer back to it, like I’m trying to do with “source.setSelected(false);”. Obviously that doesn’t work, but I imagine there is a way to do it. Any help?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JLottery2 extends JFrame implements ItemListener{
	JCheckBox[] numBox = new JCheckBox[30];
	int numChecked = 0;
	public JLottery2(){
		super("Lottery");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLayout(new FlowLayout());
		for(int i = 0; i < 30; i++){
			numBox[i] = new JCheckBox(Integer.toString(i+1), false);
			add(numBox[i]);
			numBox[i].addItemListener(this);
		}
	}
	public void itemStateChanged(ItemEvent e){
		Object source = e.getItem();
		int select = e.getStateChange();
		if(select == ItemEvent.SELECTED){
			if(numChecked < 6){
				numChecked++;
			}
			else{
				source.setSelected(false);
			}
		}
		else{
			numChecked--;
		}
	}
	public static void main(String arg[]){
		JLottery2 frame = new JLottery2();
		frame.setSize(300, 400);
		frame.setVisible(true);
	}
}

FIFO array? CircularQueue?

An idea: use an ArrayList.

use add() to add an item, then test the size
if larger than 6, remove the head item and uncheck it

with an ArrayList, any uncheck can also be removed from the list pretty easily

since its only 6 items, the exact implementation is not so crucial

Keep reference of every single one check box, and keep reference of how many are selected. When user selects 7th box, you can deselect the box you want by hand.

I don’t see what stopping you from casting [icode]source[/icode] to a JCheckBox, even if it is a little hacky.


if(numChecked < 6) {
    numChecked++;
} else{
    ((JCheckBox) source).setSelected(false);
}

That’s exactly what I wanted! Thanks!