纯Swing 绘制圆角矩形【附图】

      先上图吧



      可以清楚地看到矩形边角是没有背影的。

      如果这是你想要的结果,那请接着往下阅读其实现过程

      1、环境要求:

            1.1 JDK版本: 因为用到了AWTUtilities,而这个类随JDK6 u10或更高的版本发布的。 本人用的JRE是

                MyEclipse 8.0自带的JRE。

            

 

            2.2 JAR包需求

                 不需要任何第三方JAR包。只要JDK的版本高于或等于JDK6 u10,程序即可正常运行。

 

      2、实现过程

            结合上篇的Java 2D文档加上代码注释,实现过程还是比较容易理解的

      3、源代码

 

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Toolkit;
import java.awt.geom.RoundRectangle2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

import com.sun.awt.AWTUtilities;

/****************************************
 * <p></p>
 * @version 2012-10-8
 * @author  crazyhost QQ:949507869
 * <dd>
 * 	<dt>Encoding:</dt>
 * 	<dd>UTF-8</dd>
 * </dd>
 ****************************************/
public class RoundedRectangle extends JFrame{

	private static final long serialVersionUID = 1L;
	private JPanel panel;
	private Dimension size=new Dimension(305, 400);
	
	final int R = 66;
	final int G = 194;
	final int B = 110;
	RoundedRectangle frame = this;
	
	public RoundedRectangle(){
		
		// 设置画笔颜色,填充或描边
		final Paint p = new GradientPaint(0.0f, 0.0f, new Color(R, G, B, 100),
			getWidth(), getHeight(), new Color(R, G, B, 200), true);
		
		panel = new JPanel(){ 
			private static final long serialVersionUID = 1L;

			public void paintComponent(Graphics g){
				Graphics2D g2d = (Graphics2D) g;
				g2d.setPaint(p);
				// 设置画笔颜色为白色
				g2d.setColor(new Color(255,255,255));
				g2d.fillRect(0, 0, getWidth(), getHeight());
				
				// 设置画笔颜色为蓝色
				g2d.setColor(new Color(41,141,208));
				Shape shape = null;
				shape = new RoundRectangle2D.Double(0, 0, frame.getWidth()-1, frame.getHeight()-1, 6.5D, 6.5D);
				g2d.draw(shape);		
				
			}
		};
		this.setSize(size);
		// 去除窗体的默认修饰,这是自定义的首要前提
		this.setUndecorated(true);
		// 将panel设置为内容窗体
		this.setContentPane(panel);
		this.setVisible(true);
		//重新设定可见区域
		setVisibleRegion(frame.getWidth(),frame.getHeight());	
		center();
		
		//窗体透明
//		AWTUtilities.setWindowOpacity(frame, 0.5f);
	}
	
	//设定可见区域
	public void setVisibleRegion(int width,int height){
		Shape shape = null;
		shape = new RoundRectangle2D.Double(0, 0, width, height, 6D, 6D);
		AWTUtilities.setWindowShape(frame, shape);
	}	
	
	//设置界面显示位置
	public void center() {
		Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
		frame.setLocation((d.width - frame.getWidth()) / 2, (d.height - frame
				.getHeight()) / 2);
	}	

	public static void main(String[] args) {
		new RoundedRectangle();		
	}

}

 

 

 

猜你喜欢

转载自949507869-qq-com.iteye.com/blog/1697061