14. 11. 5. Listening to JCheckBox Events with an ItemListener

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.AbstractButton;
import java.awt.Color;

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class JCheckBoxItemListener {

    public static void main(String[] args){
    	JFrame frame = new JFrame("JCheckBox-ItemListener");
    	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	JCheckBox aCheckBox = new JCheckBox("草包");
    	
    	ItemListener itemListener = new ItemListener(){
    		public void itemStateChanged(ItemEvent e){
    			AbstractButton absButton = (AbstractButton)e.getSource();
    			Color foreground = absButton.getForeground();
    			Color background = absButton.getBackground();
    			int state = e.getStateChange();
    			
    			if(state == e.SELECTED){
    				absButton.setForeground(foreground);
    				absButton.setBackground(background);
    			}
    		}
    	};
    	
    	aCheckBox.addItemListener(itemListener);
    	frame.add(aCheckBox);
    	frame.setSize(300,200);
    	frame.setVisible(true);
    	
    }
}


你可能感兴趣的:(14. 11. 5. Listening to JCheckBox Events with an ItemListener)