Live tracking the number of selected items in a string
In Java Swing I have a simple table where in each row the name of the element and a checkbox is included. Users can select any of the elements contained by clicking in the associated check-box. I would like to have a string below the table that constantly keeps track of the number of elements 开发者_StackOverflow社区selected (E.g. "3 elements have been selected"). So as soon the use checks or un-checks an element the string automatically changes. Is it possible? Do I need to associate an event listener to every check box?
Yes, this is possible. However, you can also associate a single listener with all of your checkboxes.
JCheckbox check1 = new JCheckbox( "First" );
JCheckbox check2 = new JCheckbox( "Second" );
int numSelected = 0;
JLabel label = new JLabel("0 items selected");
ItemListener itemListener = new ItemListener() {
public void itemStateChanged( ItemEvent e ) {
if ( e.getStateChange() == ItemEvent.SELECTED )
numSelected++;
else
numSelected--;
label.setText( numSelected +
( numSelected == 1 ) " item" ? " items" + " selected" );
// might not have to explicitly re-call label.setText(..)
}
}
check1.addItemListener( itemListener );
check2.addItemListener( itemListener );
精彩评论