import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class DrawUI {
public void initUI(){
JFrame jf = new JFrame();
jf.setSize(900,900);
jf.setTitle("画图工具");
jf.setDefaultCloseOperation(3);
jf.setLocationRelativeTo(null);
FlowLayout flow = new FlowLayout();
jf.setLayout(flow);
JButton jbu = new JButton("直线");
jf.add(jbu);
JButton jbu2 = new JButton("矩形");
jf.add(jbu2);
JButton jbu3 = new JButton("等腰三角形");
jf.add(jbu3);
JButton jbu4 = new JButton("任意三角形");
jf.add(jbu4);
JButton jbu5 = new JButton("多边形" );
jf.add(jbu5);
JButton jbu6 = new JButton("曲线");
jf.add(jbu6);
JButton redButton = new JButton("红色");
jf.add(redButton);
JButton blueButton = new JButton("蓝色");
jf.add(blueButton);
jf.setVisible(true);
Graphics g = jf.getGraphics();
DrawMouse mouse = new DrawMouse();
jf.addMouseListener(mouse);
jf.addMouseMotionListener(mouse);
jbu.addActionListener(mouse);
jbu2.addActionListener(mouse);
jbu3.addActionListener(mouse);
jbu4.addActionListener(mouse);
jbu5.addActionListener(mouse);
jbu6.addActionListener(mouse);
redButton.addActionListener(mouse);
blueButton.addActionListener(mouse);
mouse.gr = g;
}
public static void main(String[] args){
DrawUI dr = new DrawUI();
dr.initUI();
}
}
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseMotionListener;
public class DrawMouse implements MouseListener,ActionListener,MouseMotionListener{
public Graphics gr;
//全局变量
public int x1,x2,y1,y2,x3,y3;
public String name;
public int flag=1;
Color currentColor = Color.BLACK;
public void actionPerformed(ActionEvent e){
name = e.getActionCommand();
System.out.println("name="+name);
if("红色".equals(name)){
currentColor = Color.RED;
}
if("蓝色".equals(name)){
currentColor = Color.blue;
}
gr.setColor(currentColor);
}
public void mouseClicked(MouseEvent e){
if("任意三角形".equals(name)) {
x3 = e.getX();
y3 = e.getY();
gr.drawLine(x1,y1,x3,y3);
gr.drawLine(x2,y2,x3,y3);
flag=1;
}
if("多边形".equals(name)){
x3 = e.getX();
y3 = e.getY();
gr.drawLine(x2,y2,x3,y3);
System.out.println("x2="+x2+"y2="+y2+"x3="+x3+"y3="+y3);
x2 = x3;
y2 = y3;
if(e.getClickCount() == 2){
gr.drawLine(x3,y3,x1,y1);
}
}
}
public void mousePressed(MouseEvent e){
if(flag==1){
x1 = e.getX();
y1 = e.getY();
}
}
public void mouseReleased(MouseEvent e){
System.out.println("释放");
if(flag==1){
x2 = e.getX();
y2 = e.getY();
}
int w = Math.abs(x2-x1);
int h = Math.abs(y2-y1);
int mx = Math.min(x1,x2);
int my = Math.min(y1,y2);
if("直线".equals(name)) {
gr.drawLine(x1, y1, x2, y2);
}
if("矩形".equals(name)) {
gr.drawRect(mx, my, w, h);
}
if("等腰三角形".equals(name)){
gr.drawLine((x1+x2)/2,y1,x1,y2);
gr.drawLine((x1+x2)/2,y1,