java学习:Graphics绘制基本图形对象

很神奇的Graphics,主要有这么几个绘制对象:线段、矩形、圆弧、椭圆、圆、多边形,字符串、(改变颜色的图形)。

<pre name="code" class="java">Graphics g;
/*
	method list
	//一、线段:
	//在当前界面坐标系中,在点 (x1,y1)和 (x2,y2) 之间画一条线 
	public abstract void drawLine(int x1,int y1,int x2,int y2)

	//二、矩形:
	//矩形左上角顶点(x,y),以及长宽
	public void drawRect(int x,int y,int width,int height)

	//三、圆弧:
	//这几个参数一直没搞太明白:
	// x - 要绘制弧的左上角的 x 坐标。
	// y - 要绘制弧的左上角的 y 坐标。
	// width - 要绘制弧的宽度。
	// height - 要绘制弧的高度。
	// startAngle - 开始角度。
	//arcAngle - 相对于开始角度而言,弧跨越的角度。
	public abstract void drawArc(int x,int y,int width,int height,int startAngle,int arcAngle)

	//四、椭圆:
	//绘制椭圆的边框。得到一个圆或椭圆,它刚好能放入由 x 、 y 、 width 和  height 参数指定的矩形中。椭圆覆盖区域的宽度为 width + 1 像素,高度为  height + 1 像素。
	//x - 椭圆的左上角的  x 坐标。
	//y - 椭圆的左上角的  y 坐标。
	//width - 椭圆的宽度。
	//height - 椭圆的高度。
	public abstract void drawOval(int x,int y,int width,int height)

	//五、 圆: 绘制圆角矩形的边框。矩形的左边缘和右边缘分别位于 x 和 x + width 。矩形的上边缘和下边缘分别位于 y 和 y + height 。
	public abstract void drawRoundRect(int x,int y,int width,int height,int arcWidth,int arcHeight)
	
	//六、字符串:
	//str - 要绘制的字符串(第一个字符会出现在x,y处)
	public abstract void drawString(String str,int x,int y)

	//七、设置颜色
	//在要绘制的图形前设置,默认黑色
	g.setColor(Color.red);

*/
g = getGraphics();

 


下面是一个简单的代码实现(偷懒只写了直线)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class draw extends JFrame
{
	Graphics grap;
	int x1,x2,y1,y2;
	public void showUI()
	{
		setSize(500,500);
		setTitle("copy of the draw");
		setLocationRelativeTo(null);//居中
		setVisible(true);
		//创建鼠标监听器,可以得知鼠标的信息
		MouseListener listener = new MouseListener()
		{
			//Executed when the mouse is clicked
			public void mouseClicked(MouseEvent e){}
			//Executed when the mouse enters interface
			public void mouseEntered(MouseEvent e){}
			//Executed When the mouse leaves the screen
			public void mouseExited(MouseEvent e){}
			//Executed When the mouse is pressed
			public void mousePressed(MouseEvent e)
			{
				x1=e.getX();
				y1=e.getY();
			}
			//Executed When the mouse is released
			public void mouseReleased(MouseEvent e)
			{
				x2=e.getX();
				y2=e.getY();
				grap.drawLine(x1,y1,x2,y2);
			}
		};
		addMouseListener(listener);
		grap = getGraphics();

	}
	public static void main(String[] agrs)
	{
		draw myDraw = new draw();
		myDraw.showUI();
	}
}


注:Graphics是一个比较丰富的类,里面还有许多其他的功能有待我去尝试,像是

draw3Drect()grap.draw3DRect(x, y, width, height, raised);

据说能够画出3D的矩形,但是我还不会用......

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值