📄 drawfigurepanel.java
字号:
package drawfigure;import java.awt.*;import java.awt.event.*;import java.math.*;public class DrawFigurePanel extends Panel { Point startPoint = new Point(0,0); Point lastEndPoint = new Point(0,0); Point thisEndPoint = new Point(0,0); Point finalEndPoint = new Point(0,0); public String drawStyle = null; boolean figureState = false; boolean firstDraw = true; public DrawFigurePanel(){ addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent e){ startPoint.x = lastEndPoint.x = thisEndPoint.x = e.getPoint().x; startPoint.y = lastEndPoint.y = thisEndPoint.y = e.getPoint().y; setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); figureState = true; } public void mouseReleased(MouseEvent e){ finalEndPoint.x = e.getPoint().x; finalEndPoint.y = e.getPoint().y; setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); Graphics g = getGraphics(); g.setXORMode(getBackground()); if(firstDraw) drawFigure(g,startPoint,finalEndPoint); g.dispose(); figureState = false; firstDraw = true; } }); addMouseMotionListener(new MouseMotionAdapter(){ public void mouseDragged(MouseEvent e){ Graphics g = getGraphics(); g.setXORMode(getBackground()); if(figureState){ lastEndPoint.x = thisEndPoint.x; lastEndPoint.y = thisEndPoint.y; thisEndPoint.x = e.getPoint().x; thisEndPoint.y = e.getPoint().y; } if(firstDraw){ drawFigure(g,startPoint,thisEndPoint); firstDraw = false; }else { drawFigure(g,startPoint,lastEndPoint); drawFigure(g,startPoint,thisEndPoint); } g.dispose(); } }); } public void setDrawStyle(String style){ drawStyle = style; } public void drawFigure(Graphics g,Point start,Point end){ if(drawStyle == "line"){ g.drawLine(start.x,start.y,end.x,end.y); }else if(drawStyle == "rect"){ int x = start.x ,y = start.y; if(end.x < start.x) x = end.x; if(end.y < start.y) y = end.y; g.drawRect(x,y,Math.abs(end.x - start.x),Math.abs(end.y - start.y)); }else if(drawStyle == "oval"){ int x = start.x ,y = start.y; if(end.x < start.x) x = end.x; if(end.y < start.y) y = end.y; g.drawOval(x,y,Math.abs(end.x-start.x),Math.abs(end.y - start.y)); } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -