使用定制JCheckBox 实现 “伪”三态复选框

项目本来需要一个带有复选框的树形控件,于是我找到了JIDE里的一个开源控件,研究了一下,发现无法实现需要的功能,而我自己又比较水,在网上找到的其他代码都不会用,只好自己写一个简单的,有些“旁门左道”的感觉...下面是实现代码:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.util.Random;

import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;

public class HGCheckBoxTest extends JCheckBox implements ActionListener{
	public static final int ALL_SELECTED =1;
	public static final int NONE_SELECTED = 2;
	public static final int SOME_SELECTED = 3;
	int state = NONE_SELECTED;
	public HGCheckBoxTest(int state){
		super();
		this.addActionListener(this);
		this.state = state;
	}
	public HGCheckBoxTest(Action a){
		super(a);		
	}
	
	public void paintComponent(Graphics g){
		if(state == SOME_SELECTED){
			
			this.setSelected(true);
			float[] my_kernel = {
		            0.10f, 0.10f, 0.10f,
		            0.10f, 0.20f, 0.10f,
		            0.10f, 0.10f, 0.10f };
		    ConvolveOp op = new ConvolveOp(new Kernel(3,3, my_kernel), ConvolveOp.EDGE_NO_OP, null);
		    BufferedImage buf = new BufferedImage(getWidth(),getHeight(), BufferedImage.TYPE_INT_RGB);
		    super.paintComponent(buf.getGraphics());
		    Image img = op.filter(buf,null);
		    g.drawImage(img,0,0,null);
		       
		}else{
			if(state==ALL_SELECTED){
				this.setSelected(true);
			}else if(state == NONE_SELECTED){
				this.setSelected(false);
			}
			super.paintComponent(g);
			
			return;
		}
	}
	public int getState() {
		return state;
	}
	public void setState(int state) {
		this.state = state;
	}
	static int i =1;
	public static void main(String[] args){
		JFrame frame = new JFrame("test CheckBox");
		final HGCheckBoxTest testBox = new HGCheckBoxTest(3); 
		JButton control = new JButton("change");
		control.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				int test = i++%3+1;				
				( testBox).setState(test);
				testBox.repaint();
			}
			
		});

		frame.getContentPane().add(testBox);
		frame.getContentPane().add("South",control);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(new Dimension(200,200));
		frame.setVisible(true);
	}
	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		int test = i++%2+1;	

		this.setState(test);
		
		//System.out.println(this.isSelected());
		//System.out.println(this.getState());
	}
}

 程序实例截图:


使用定制JCheckBox 实现 “伪”三态复选框
 项目截图:


使用定制JCheckBox 实现 “伪”三态复选框
 舍弃JIDE方案截图:


使用定制JCheckBox 实现 “伪”三态复选框
 原因:无法通过代码设置叶子节点的选择状态。

你可能感兴趣的:(java,swing)