Swing 动态错误提示框

最近写了个swing 动态提示错误的提示框,本来想放在项目中的,被否掉了,拿出来共享一下,共同提高:

 

package errborder;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.border.AbstractBorder;

public class BlinkErrorBorder extends AbstractBorder implements ActionListener{
	private int thickness = 5;
	private float alpha = thickness;
	private Color color = Color.RED;
	private Timer timer ;
	private AlphaComposite composite;
	private final float[] blinkArray = new float[]{1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
												  -1.0f,-1.0f,-1.0f,-1.0f,-1.0f,-1.0f,-1.0f};
	
	public BlinkErrorBorder(Color color, int thickness){
		this.color = color;
		this.thickness = thickness;
		this.alpha = thickness;
		composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);	
		timer = new Timer(120, this);
	}
	
	public void startBlink(){
		timer.start();
	}
	
	public void stopBlink(){
		timer.stop();
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		JFrame frame = new JFrame();
		BlinkErrorBorder err = new BlinkErrorBorder(Color.RED,3);
		JTextField text = new JTextField();
		text.setBorder(err);
		err.startBlink();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		frame.getContentPane().add(text);
		frame.setSize(400,400);
		frame.setVisible(true);
	}
	
	 public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
		Graphics2D g2d = (Graphics2D) g.create();
		g2d.setColor(color);
		
		for(int i = 0; i < thickness; i++)  {
			composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (thickness-i)/alpha);
			g2d.setComposite(composite);
			g2d.drawRoundRect(x+i, y+i, width-i-i-1, height-i-i-1, thickness, thickness);
		}		
		c.repaint();
	 }
	 public Insets getBorderInsets(Component c)       {
	        return new Insets(thickness, thickness, thickness, thickness);
	 }
	 
	 int tempI = 0;
	@Override
	public void actionPerformed(ActionEvent e) {
		alpha = alpha+blinkArray[tempI];
		tempI++;
		tempI = tempI%(blinkArray.length);		
	}

}

 

你可能感兴趣的:(Swing,Swing,错误提示,动态border)