从一开始接触计算机,我们就知道计算机的 开始菜单-程序-附件中有个画图工具。
在当时这个工具也是的确非常的好用,那么今天我们要做的是一个简单的画板。
这个画板能够实现画直线,画矩形,画圆角矩形,画圆,画三角形这五个功能。
这便是我用事件机制做出来的第一个程序。
首先我们分析一下如何实现这个画板。首先建立一个窗体,在窗体的北部添加5个按钮,
分别为Line,Rectangle,RoundRect,Round,Triangle
然后创建画布对象,用窗体类继承JFrame,并获取画布对象。
//设置窗体继承JFrame
public class DrawTable extends JFrame{
//定义画图模式,默认为直线
private String drawshape= "Line";
public void initUI(){
//设置窗体大小
this.setSize(new Dimension(600, 500));
//设置窗体的位置居中
this.setLocationRelativeTo(null);
//设置窗体的关闭按钮
this.setDefaultCloseOperation(3);
//设置窗体不可以调节大小
this.setResizable(false);
//建立北部面板
JPanel panelnorth = new JPanel();
//建立五个按钮对象
JButton Line = new JButton("Line");
JButton Rect = new JButton("Rectangle");
JButton RectRound = new JButton("RoundRect");
JButton Round = new JButton("Round");
JButton Triangle = new JButton("Triangle");
//将5个按钮添加到面板上
panelnorth.add(Line);
panelnorth.add(Rect);
panelnorth.add(RectRound);
panelnorth.add(Round);
panelnorth.add(Triangle);
//将面板添加到窗体的北部
this.add(panelnorth,BorderLayout.NORTH);
//建立画布面板
JPanel drawpanel = new JPanel();
//设置画布面板背景为白色
drawpanel.setBackground(Color.WHITE);
//将画布面板添加到窗体中央
this.add(drawpanel,BorderLayout.CENTER);
//设置窗体可见
this.setVisible(true);
//获取画布对象
Graphics g = drawpanel.getGraphics();
//实例化画布监听器对象
DrawListener dl = new DrawListener(g,this);
//在画布面板上添加监听器
drawpanel.addMouseListener(dl);
}
//获取画布模式的方法
public String getshape(){
return drawshape;
}
}
下面就是对按钮的监听,我们可以创建一个匿名内部类,来获取按钮的actioncommend
ActionListener al = new ActionListener(){
public void actionPerformed(ActionEvent e) {
//获取按钮对应的字符串
drawshape = e.getActionCommand();
}
};
//在按钮上添加监听器
Line.addActionListener(al);
Rect.addActionListener(al);
RectRound.addActionListener(al);
Round.addActionListener(al);
Triangle.addActionListener(al);
创建好窗体以后,我们开始设置画布面板的监听器,即为上面的DrawListener
然后我们就要建立监听器,获取鼠标点的坐标,并且调用相应的方法。
//画线的方法
public void drawLine() {
g.drawLine(x1, y1, x2, y2);
}
//画矩形的方法,先交换使得x1,y1最小,然后画矩形
public void drawRect() {
if (x1 > x2) {
int t = x1;
x1 = x2;
x2 = t;
}
if (y1 > y2) {
int t = y1;
y1 = y2;
y2 = t;
}
g.drawRect(x1, y1, x2 - x1, y2 - y1);
}
//与画矩形的原理相同
public void drawRectRound() {
if (x1 > x2) {
int t = x1;
x1 = x2;
x2 = t;
}
if (y1 > y2) {
int t = y1;
y1 = y2;
y2 = t;
}
g.drawRoundRect(x1, y1, x2 - x1, y2 - y1, 20, 20);
}
//画圆的方法
public void drawRound() {
if (x1 > x2) {
int t = x1;
x1 = x2;
x2 = t;
}
if (y1 > y2) {
int t = y1;
y1 = y2;
y2 = t;
}
//获取半径
int r = Math.min(x2 - x1, y2 - y1);
g.drawOval(x1, y1, r, r);
}
//画三角形的方法,先判断,如果是true,就画线并把两个点存起来,下一次是false,就连接另外两条线段
public void drawtriangle() {
if (bol) {
drawLine();
tx1 = x1;
ty1 = y1;
tx2 = x2;
ty2 = y2;
bol = false;
} else {
g.drawLine(tx1, ty1, x2, y2);
g.drawLine(tx2, ty2, x2, y2);
bol = true;
}
}
这样我们就能够在画布上画出直线,矩形等好看的图形啦~