前言
画图板在1.0版本实现了简单的画图功能,这期将让画图板有更多的图形和颜色可以选择。
本次所需用到的开发包:
- java.awt
- java.awt.event
- javax.swing
一、更多的图形
这次将加入4种图形可供选择,分别是等腰三角形,三角形,多边形和长方体,并使用按钮实现功能
等腰三角形
public class DrawListen implements MouseListener{
int x1,y1,x2,y2;
Graphics gr;
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
x1 = x;
y1 = y;
}
public void mouseReleased(MouseEvent e) {
int x = e.getX();
int y = e.getY();
x2 = x;
y2 = y;
int tx = (x1 + x2)/2;
int ty = y1;
gr.drawLine(tx, ty, x1, y2);
gr.drawLine(tx, ty, x2, y2);
gr.drawLine(x2, y2, x1, y2);
}
......
}
三角形
public class DrawListen implements MouseListener{
int x3,x4,x5,y3,y4,y5;
int count = 0;
Graphics gr;
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
gr.fillOval(x - 3, y - 3, 6, 6);//点击提示,形成点
if(count==0) {
x3 = x;
y3 = y;
count++;
}else if(count==1) {
x4 = x;
y4 = y;
gr.drawLine(x3, y3, x4, y4);
count++;
}else if(count==2) {
x5 = x;
y5 = y;
gr.drawLine(x3, y3, x5, y5);
gr.drawLine(x5, y5, x4, y4);
count = 0;
}
}
......
}
多边形
public class DrawListen implements MouseListener{
int x3,x4,x5,y3,y4,y5;
int count = 0;
Graphics gr;
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
gr.fillOval(x - 3, y - 3, 6, 6);//点击提示
if(count==0) {
x3 = x;
y3 = y;
x4 = x;
y4 = y;
count++;