⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 drawshapefillcolortest.java

📁 编程之道--java程序设计入门源代码
💻 JAVA
字号:
/**
 * 在面板中绘制2D图形,为不同的图形设置不同的颜色,测试填充形体的顺序
 */

import javax.swing.JFrame;
import java.awt.Toolkit;
import java.awt.Image;
import java.awt.Dimension;
import java.awt.Container;
import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.geom.Rectangle2D;
import java.awt.geom.Line2D;
import java.awt.geom.Ellipse2D;
import java.awt.Graphics2D;
import java.awt.Color;

public class DrawShapeFillColorTest
{
	public static void main(String[] args)
	{
		BlankFrame frame = new BlankFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.show();
	} 
}

/**
 * 这是定制自己的框架
 */
class BlankFrame extends JFrame
{
	private static final int WIDTH = 400;
	private static final int HEIGHT = 300;
	public BlankFrame()
	{
		Container con = getContentPane();//得到了内容窗格
		
		Toolkit kit = Toolkit.getDefaultToolkit();
		Dimension screenSize = kit.getScreenSize();
		int width = screenSize.width;
		int height = screenSize.height;
		int x = (width - WIDTH)/2;
		int y = (height - HEIGHT)/2;
		setLocation(x, y);//设置坐标起点
		setSize(WIDTH, HEIGHT);//设置框架的大小
		Image image = kit.getImage("duke.gif");// duke.gif为图像文件名
		setIconImage(image);//设置框架图标
		setTitle("这是我美化的框架");
		setResizable(false);
		
		StringPanel panel = new StringPanel();//得到定制的面板
		con.add(panel);//将面板添加到内容窗格中
	}
}

/**
 * 这是继承了JPanel面板类,它重载了绘制的方法
 */
class StringPanel extends JPanel
{
	public static final double WIDTH = 200;
	public static final double HEIGHT = 100;
	public static final double X = 100;
	public static final double Y = 100;
	
	public StringPanel()
	{
		setBackground(Color.black);//设置背景色为黑色
	}
	
	public void paintComponent(Graphics g)
	{
		super.paintComponent(g);
		Graphics2D g2 = (Graphics2D)g;
		
		//绘制矩形
		Rectangle2D rec = new Rectangle2D.Double(X, Y, WIDTH, HEIGHT);
		g2.setPaint(Color.red);//设置矩形为红色
		g2.draw(rec);
		
		//得到矩形的中心坐标值
		double centerX = rec.getCenterX();
		double centerY = rec.getCenterY();
		
		//根据矩形的中心,绘制与短径相切同心圆形
		Ellipse2D circle2 = new Ellipse2D.Double();
		circle2.setFrameFromCenter(centerX, centerY, centerX + HEIGHT/2, centerY + HEIGHT/2);
		g2.setPaint(Color.orange);
		g2.draw(circle2);
		g2.setPaint(Color.blue);
		g2.fill(circle2);
		
		//根据矩形的外框,绘制内接椭圆
		Ellipse2D e = new Ellipse2D.Double();
		e.setFrame(rec);
		g2.setPaint(new Color(100, 200, 255));
		g2.draw(e);
		g2.setPaint(Color.white);
		g2.fill(e);
		
		//根据矩形的中心,绘制与长径相切同心圆形
		Ellipse2D circle1 = new Ellipse2D.Double();
		circle1.setFrameFromCenter(centerX, centerY, centerX + WIDTH/2, centerY + WIDTH/2);
		g2.setPaint(Color.green);//设置圆1为绿色
		g2.draw(circle1);
		
		//根据矩形的两点绘制直线
		Line2D line = new Line2D.Double(X, Y, X + WIDTH, Y + HEIGHT);
		g2.draw(line);		
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -