文件组织
代码
package drawboard;import javax.swing.JFrame;public class DrawBoard {public static void main(String[] args) {DrawBoardFrame db=new DrawBoardFrame();db.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}
package drawboard;import javax.swing.*;public class DrawBoardFrame extends JFrame{public static final int DEFAULT_W=600;public static final int DEFAULT_H=500;public DrawBoardFrame(){setTitle("画板");setSize(DEFAULT_W,DEFAULT_H);DrawBoardPanel panel=new DrawBoardPanel();getContentPane().add(panel);setVisible(true);}}
package drawboard;import java.awt.*;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.event.MouseMotionListener;import java.awt.geom.Line2D;import javax.swing.*;public class DrawBoardPanel extends JPanel{int x1,y1,x2,y2;public DrawBoardPanel(){addMouseMotionListener(new MouseMotionListener() {public void mouseDragged(MouseEvent e) {Graphics2D g=(Graphics2D)getGraphics();//获取鼠标位置x2=e.getX();y2=e.getY();g.draw(new Line2D.Double(x1,y1,x2,y2));x1=x2;y1=y2;g.dispose();}public void mouseMoved(MouseEvent e) {double tx=e.getX();double ty=e.getY();System.out.println("鼠标当前坐标:("+tx+","+ty+')');};});addMouseListener(new MouseAdapter(){public void mousePressed(MouseEvent e){x1=e.getX();y1=e.getY();}});}}
效果
PS:较早时候写的,可能不符合现在的规范,仅作参考。
如果觉得《【Java GUI】简单铅笔画图程序》对你有帮助,请点赞、收藏,并留下你的观点哦!