1.首先我们需要创建一个窗口
JFrame f1=new JFrame();
f1.setTitle("直线");//设置标题
f1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);//设置关闭方式
f1.setSize(800,800);//界面尺寸
FlowLayout fl = new FlowLayout();//布局
f1.setLayout(fl);
2.添加鼠标监听器
DrawListener a1 = new DrawListener();// 设置监听器
f1.addMouseListener(a1);
3.完成监听器的代码
public class DrawListener implements java.awt.event.MouseListener {
int x1, x2, y1, y2;
java.awt.Graphics g = null;
public void mousePressed(MouseEvent e) {
x1 = e.getX();
y1 = e.getY();// 获取鼠标按压时坐标
}
public void mouseReleased(MouseEvent e) {
x2 = e.getX();
y2 = e.getY();// 获取鼠标释放时坐标
g.drawLine(x1, y1, x2, y2);//完成直线的绘制
}
4.进行可视化并完成画笔的获取
f1.setVisible(true);
// 获取画笔
a1.g =f1.getGraphics();//获取一定在可视化后面