Swing 自定义控件学习笔记

这篇博客记录了使用Swing开发可拉伸矩形控件的学习过程,主要涉及自定义控件的实现,包括`paintComponent`、`paintBorder`、`paintChildren`和`paint`等关键方法。通过扩展`AWT Rectangle`类和创建`RectBound`控件,实现了可拖动调整大小和位置的矩形框功能。

做一个用Swing开发的小工具,需要用到一个可拉伸的矩形控件,学习了下极客学院的自定义控件的视频教程记录一下~^_^

自定义控件主要实现Jcomponent中的4个方法来绘制控件:

  • paintComponent(Graphics)  绘制组件自身
  • paintBorder(Graphics)  绘制组件border边框
  • paintChildren(Graphics) 绘制该控件内部的子控件
  • paint(Graphics) 依次调用上面的函数来进行绘制
调用的次序依次是paintComponent、paintBorder、paintChildren方法,其中Graphics对象进行具体的绘制,可以强转为Graphics2D获得更多的绘图API,如消除锯齿等。

实现可拉伸的矩形框参考 http://blog.youkuaiyun.com/fancy888/article/details/7740958

主要实现:

  • 绘制矩形并绘制8个用来调整大小的手柄
  • 拖动手柄可以调整矩形框的大小
  • 在矩形框内部可以拖动整个矩形框的位置

一共两个类

PointRectangle:扩展了AWT的Rectangle类,按左上角和右下角两个坐标点来定义矩形(AWT默认是按左上角坐标和长宽来定义矩形的)

import java.awt.Rectangle;

public class PointRectangle extends Rectangle {

	private static final long serialVersionUID = -2465363144347743255L;

	int x1, x2, y1, y2;

	public PointRectangle(int x1, int y1, int x2, int y2) {
		this.x1 = x = x1;
		this.x2 = x2;
		this.y1 = y = y1;
		this.y2 = y2;
		width = x2 - x1;
		height = y2 - y1;
		if (x2 < x1) {
			x = x2;
			width = x1 - x2;
		}
		if (y2 < y1) {
			y = y2;
			height = y1 - y2;
		}
	}

	public PointRectangle(Rectangle rectangle) {
		super(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
		this.x1 = rectangle.x;
		this.y1 = rectangle.y;
		this.x2 = rectangle.x + rectangle.width;
		this.y2 = rectangle.y + rectangle.height;
	}

}

RectBound :自定义的矩形边框控件


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值