做一个用Swing开发的小工具,需要用到一个可拉伸的矩形控件,学习了下极客学院的自定义控件的视频教程记录一下~^_^
自定义控件主要实现Jcomponent中的4个方法来绘制控件:
- paintComponent(Graphics) 绘制组件自身
- paintBorder(Graphics) 绘制组件border边框
- paintChildren(Graphics) 绘制该控件内部的子控件
- paint(Graphics) 依次调用上面的函数来进行绘制
实现可拉伸的矩形框参考 http://blog.csdn.net/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 :自定义的矩形边框控件