java编程实现屏幕截图(截屏)代码总结
本文实例总结了常见的java编程实现屏幕截图方法。分享给大家供大家参考,具体如下:
方法一:
importjava.awt.Desktop; importjava.awt.Dimension; importjava.awt.Rectangle; importjava.awt.Robot; importjava.awt.Toolkit; importjava.awt.image.BufferedImage; importjava.io.File; importjavax.imageio.ImageIO; publicclassCaptureScreen{ publicstaticvoidcaptureScreen(StringfileName,Stringfolder)throwsException{ DimensionscreenSize=Toolkit.getDefaultToolkit().getScreenSize(); RectanglescreenRectangle=newRectangle(screenSize); Robotrobot=newRobot(); BufferedImageimage=robot.createScreenCapture(screenRectangle); //保存路径 FilescreenFile=newFile(fileName); if(!screenFile.exists()){ screenFile.mkdir(); } Filef=newFile(screenFile,folder); ImageIO.write(image,"png",f); //自动打开 if(Desktop.isDesktopSupported() &&Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) Desktop.getDesktop().open(f); } publicstaticvoidmain(String[]args){ try{ captureScreen("e:\\你好","11.png"); }catch(Exceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } }
方法二:
packagecom.qiu.util; importjava.io.*; importjavax.swing.*; importjava.awt.*; importjava.awt.event.*; importjava.awt.image.*; importjavax.imageio.*; /** *一个简单的屏幕抓图 * **/ publicclassScreenCapture{ //testmain publicstaticvoidmain(String[]args)throwsException{ Stringuserdir=System.getProperty("user.dir"); FiletempFile=newFile("d:","temp.png"); ScreenCapturecapture=ScreenCapture.getInstance(); capture.captureImage(); JFrameframe=newJFrame(); JPanelpanel=newJPanel(); panel.setLayout(newBorderLayout()); JLabelimagebox=newJLabel(); panel.add(BorderLayout.CENTER,imagebox); imagebox.setIcon(capture.getPickedIcon()); capture.saveToFile(tempFile); capture.captureImage(); imagebox.setIcon(capture.getPickedIcon()); frame.setContentPane(panel); frame.setSize(400,300); frame.show(); System.out.println("Over"); } privateScreenCapture(){ try{ robot=newRobot(); }catch(AWTExceptione){ System.err.println("InternalError:"+e); e.printStackTrace(); } JPanelcp=(JPanel)dialog.getContentPane(); cp.setLayout(newBorderLayout()); labFullScreenImage.addMouseListener(newMouseAdapter(){ publicvoidmouseReleased(MouseEventevn){ isFirstPoint=true; pickedImage=fullScreenImage.getSubimage(recX,recY,recW, recH); dialog.setVisible(false); } }); labFullScreenImage.addMouseMotionListener(newMouseMotionAdapter(){ publicvoidmouseDragged(MouseEventevn){ if(isFirstPoint){ x1=evn.getX(); y1=evn.getY(); isFirstPoint=false; }else{ x2=evn.getX(); y2=evn.getY(); intmaxX=Math.max(x1,x2); intmaxY=Math.max(y1,y2); intminX=Math.min(x1,x2); intminY=Math.min(y1,y2); recX=minX; recY=minY; recW=maxX-minX; recH=maxY-minY; labFullScreenImage.drawRectangle(recX,recY,recW,recH); } } publicvoidmouseMoved(MouseEvente){ labFullScreenImage.drawCross(e.getX(),e.getY()); } }); cp.add(BorderLayout.CENTER,labFullScreenImage); dialog.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); dialog.setAlwaysOnTop(true); dialog.setMaximumSize(Toolkit.getDefaultToolkit().getScreenSize()); dialog.setUndecorated(true); dialog.setSize(dialog.getMaximumSize()); dialog.setModal(true); } //SingletonPattern publicstaticScreenCapturegetInstance(){ returndefaultCapturer; } /**捕捉全屏慕*/ publicIconcaptureFullScreen(){ fullScreenImage=robot.createScreenCapture(newRectangle(Toolkit .getDefaultToolkit().getScreenSize())); ImageIconicon=newImageIcon(fullScreenImage); returnicon; } /**捕捉屏幕的一个矫形区域*/ publicvoidcaptureImage(){ fullScreenImage=robot.createScreenCapture(newRectangle(Toolkit .getDefaultToolkit().getScreenSize())); ImageIconicon=newImageIcon(fullScreenImage); labFullScreenImage.setIcon(icon); dialog.setVisible(true); } /**得到捕捉后的BufferedImage*/ publicBufferedImagegetPickedImage(){ returnpickedImage; } /**得到捕捉后的Icon*/ publicImageIcongetPickedIcon(){ returnnewImageIcon(getPickedImage()); } /** *储存为一个文件,为PNG格式 * *@deprecatedreplacedbysaveAsPNG(Filefile) **/ @Deprecated publicvoidsaveToFile(Filefile)throwsIOException{ ImageIO.write(getPickedImage(),defaultImageFormater,file); } /**储存为一个文件,为PNG格式*/ publicvoidsaveAsPNG(Filefile)throwsIOException{ ImageIO.write(getPickedImage(),"png",file); } /**储存为一个JPEG格式图像文件*/ publicvoidsaveAsJPEG(Filefile)throwsIOException{ ImageIO.write(getPickedImage(),"JPEG",file); } /**写入一个OutputStream*/ publicvoidwrite(OutputStreamout)throwsIOException{ ImageIO.write(getPickedImage(),defaultImageFormater,out); } //singletondesignpattern privatestaticScreenCapturedefaultCapturer=newScreenCapture(); privateintx1,y1,x2,y2; privateintrecX,recY,recH,recW;//截取的图像 privatebooleanisFirstPoint=true; privateBackgroundImagelabFullScreenImage=newBackgroundImage(); privateRobotrobot; privateBufferedImagefullScreenImage; privateBufferedImagepickedImage; privateStringdefaultImageFormater="png"; privateJDialogdialog=newJDialog(); } /**显示图片的Label*/ classBackgroundImageextendsJLabel{ publicvoidpaintComponent(Graphicsg){ super.paintComponent(g); g.drawRect(x,y,w,h); Stringarea=Integer.toString(w)+"*"+Integer.toString(h); g.drawString(area,x+(int)w/2-15,y+(int)h/2); g.drawLine(lineX,0,lineX,getHeight()); g.drawLine(0,lineY,getWidth(),lineY); } publicvoiddrawRectangle(intx,inty,intwidth,intheight){ this.x=x; this.y=y; h=height; w=width; repaint(); } publicvoiddrawCross(intx,inty){ lineX=x; lineY=y; repaint(); } intlineX,lineY; intx,y,h,w; }
方法三:
因为有最小化到系统托盘,还是需要一张名为bg.gif作为托盘图标,图片应放在同级目录下,否则会空指针异常。
主要的截屏代码部分是:
Robotro=newRobot(); Toolkittk=Toolkit.getDefaultToolkit(); Dimensiondi=tk.getScreenSize(); Rectanglerec=newRectangle(0,0,di.width,di.height); BufferedImagebi=ro.createScreenCapture(rec);
(源代码来源于CSDN)
importjava.awt.*; importjava.awt.datatransfer.DataFlavor; importjava.awt.datatransfer.Transferable; importjava.awt.datatransfer.UnsupportedFlavorException; importjava.awt.event.*; importjavax.swing.*; importjava.io.*; importjavax.imageio.*; importjava.awt.image.*; publicclassCaptureScreenextendsJFrameimplementsActionListener{ privateJButtonstart,cancel,saveAll; privateJPanelc; privateBufferedImageget; privateJTabbedPanejtp;//一个放置很多份图片 privateintindex;//一个一直会递增的索引,用于标认图片 privateJRadioButtonjava,system;//JAVA界面,系统界面 /**CreatesanewinstanceofCaptureScreen*/ publicCaptureScreen(){ super("屏幕截取软件(第三版)"); try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch(Exceptionexe){ exe.printStackTrace(); } initWindow(); initOther(); initTrayIcon(); } privatevoidinitOther(){ jtp=newJTabbedPane(JTabbedPane.TOP,JTabbedPane.SCROLL_TAB_LAYOUT); } privatevoidinitWindow(){ start=newJButton("开始截取"); saveAll=newJButton("保存所有"); cancel=newJButton("退出"); start.addActionListener(this); saveAll.addActionListener(this); cancel.addActionListener(this); JPanelbuttonJP=newJPanel(); c=newJPanel(newBorderLayout()); c.setBackground(Color.BLACK); JLabeljl=newJLabel("屏幕截取",JLabel.CENTER); jl.setFont(newFont("黑体",Font.BOLD,40)); jl.setForeground(Color.RED); c.add(jl,BorderLayout.CENTER); buttonJP.add(start); buttonJP.add(saveAll); buttonJP.add(cancel); buttonJP.setBorder(BorderFactory.createTitledBorder("公共操作区")); JPaneljp=newJPanel();//放两个单选按钮的面板 jp.add(java=newJRadioButton("java界面")); jp.add(system=newJRadioButton("系统界面",true)); java.addActionListener(this); system.addActionListener(this); jp.setBorder(BorderFactory.createTitledBorder("界面风格")); ButtonGroupbg=newButtonGroup(); bg.add(java); bg.add(system); JPanelall=newJPanel(); all.add(jp); all.add(buttonJP); this.getContentPane().add(c,BorderLayout.CENTER); this.getContentPane().add(all,BorderLayout.SOUTH); this.setSize(500,400); this.setLocationRelativeTo(null); this.setVisible(true); this.setAlwaysOnTop(true); this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); this.addWindowListener(newWindowAdapter(){ publicvoidwindowClosing(WindowEventwe){ CaptureScreen.this.setVisible(false); } }); } privatevoidinitTrayIcon(){ try{ SystemTrayst=SystemTray.getSystemTray(); Imageim=ImageIO.read(this.getClass().getResource("bg.gif")); PopupMenupm=newPopupMenu("弹出菜单"); pm.add(newMenuItem("关于")).addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEventae){ JOptionPane.showMessageDialog(CaptureScreen.this,"<html><Fontcolor=red><center><h2>关于</h2></center></Font>"+ "这是一款纯JAVA的屏幕截取程序<br>在以前的基础上增加了一些常用的功能,<br>"+ "比如,批量保存,多幅截取,复制到系统粘帖板...<br>"+ "在使用过程中有任何问题,欢迎联系.<br>"+ "<Fontsize=5color=blue>作者:千里冰封<br>"+ "<i>QQ:24325142</i><br></Font></html>"); } }); pm.addSeparator(); pm.add(newMenuItem("显示主窗口")).addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEventae){ CaptureScreen.this.setVisible(true); } }); pm.add(newMenuItem("开始截取")).addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEventae){ doStart(); } }); pm.add(newMenuItem("退出程序")).addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEventae){ System.exit(0); } }); TrayIconti=newTrayIcon(im,"JAVA屏幕截取",pm); st.add(ti); ti.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEventae){ CaptureScreen.this.setVisible(true); } }); }catch(Exceptionexe){ exe.printStackTrace(); } } privatevoidupdates(){ this.setVisible(true); if(get!=null){ //如果索引是0,则表示一张图片都没有被加入过, //则要清除当前的东西,重新把tabpane放进来 if(index==0){ c.removeAll(); c.add(jtp,BorderLayout.CENTER); }else{//否则的话,直接对tabpane添加面板就可以了 //就什么都不用做了 } PicPanelpic=newPicPanel(get); jtp.addTab("图片"+(++index),pic); jtp.setSelectedComponent(pic); SwingUtilities.updateComponentTreeUI(c); } } privatevoiddoStart(){ try{ this.setVisible(false); Thread.sleep(500);//睡500毫秒是为了让主窗完全不见 Robotro=newRobot(); Toolkittk=Toolkit.getDefaultToolkit(); Dimensiondi=tk.getScreenSize(); Rectanglerec=newRectangle(0,0,di.width,di.height); BufferedImagebi=ro.createScreenCapture(rec); JFramejf=newJFrame(); Temptemp=newTemp(jf,bi,di.width,di.height); jf.getContentPane().add(temp,BorderLayout.CENTER); jf.setUndecorated(true); jf.setSize(di); jf.setVisible(true); jf.setAlwaysOnTop(true); }catch(Exceptionexe){ exe.printStackTrace(); } } /** *公共方法,处理保存所有的图片 */ publicvoiddoSaveAll(){ if(jtp.getTabCount()==0){ JOptionPane.showMessageDialog(this,"图片不能为空!!","错误",JOptionPane.ERROR_MESSAGE); return; } JFileChooserjfc=newJFileChooser("."); jfc.addChoosableFileFilter(newGIFfilter()); jfc.addChoosableFileFilter(newBMPfilter()); jfc.addChoosableFileFilter(newJPGfilter()); jfc.addChoosableFileFilter(newPNGfilter()); inti=jfc.showSaveDialog(this); if(i==JFileChooser.APPROVE_OPTION){ Filefile=jfc.getSelectedFile(); Stringabout="PNG"; Stringext=file.toString().toLowerCase(); javax.swing.filechooser.FileFilterff=jfc.getFileFilter(); if(ffinstanceofJPGfilter){ about="JPG"; }elseif(ffinstanceofPNGfilter){ about="PNG"; }elseif(ffinstanceofBMPfilter){ about="BMP"; }elseif(ffinstanceofGIFfilter){ about="GIF"; } if(ext.endsWith(about.toLowerCase())){ ext=ext.substring(0,ext.lastIndexOf(about.toLowerCase())); } //起一个线程去保存这些图片并显示出进度条 newSaveAllThread(ext,about).setVisible(true); } } //专门用来保存所有图片的线程类,它还要显示出保存的进度条 privateclassSaveAllThreadextendsJDialogimplementsRunnable{ privateStringname;//文件名头部份 privateStringext;//文件格式 privateJProgressBarjpb;//一个进度条 privateJLabelinfo;//一个信息显示条 privateintallTask,doneTask;//所有任务,已完成任务 publicSaveAllThread(Stringname,Stringext){ super(CaptureScreen.this,"保存",true); this.name=name; this.ext=ext; initWindow(); } privatevoidinitWindow(){ jpb=newJProgressBar(); allTask=jtp.getTabCount(); jpb.setMaximum(allTask); jpb.setMinimum(0); jpb.setValue(0); jpb.setStringPainted(true); setProgressBarString(); info=newJLabel("正在保存到:"); this.getContentPane().setBackground(Color.CYAN); this.add(info,BorderLayout.NORTH); this.add(jpb,BorderLayout.SOUTH); this.setUndecorated(true); this.setSize(300,100); this.setLocationRelativeTo(CaptureScreen.this); newThread(this).start(); } privatevoidsetProgressBarString(){ jpb.setString(""+doneTask+"/"+allTask); } publicvoidrun(){ try{ for(inti=0;i<allTask;i++){ PicPanelpp=(PicPanel)jtp.getComponentAt(i); BufferedImageimage=pp.getImage(); Filef=newFile(name+(doneTask+1)+"."+ext.toLowerCase()); info.setText("<html><b>正在保存到:</b><br>"+f.toString()+"</html>"); ImageIO.write(image,ext,f); doneTask++; jpb.setValue(doneTask); setProgressBarString(); Thread.sleep(500); } JOptionPane.showMessageDialog(this,"保存完毕!!"); this.dispose(); }catch(Exceptionexe){ exe.printStackTrace(); this.dispose(); } } } /** *公用的处理保存图片的方法 *这个方法不再私有了 */ publicvoiddoSave(BufferedImageget){ try{ if(get==null){ JOptionPane.showMessageDialog(this,"图片不能为空!!","错误",JOptionPane.ERROR_MESSAGE); return; } JFileChooserjfc=newJFileChooser("."); jfc.addChoosableFileFilter(newGIFfilter()); jfc.addChoosableFileFilter(newBMPfilter()); jfc.addChoosableFileFilter(newJPGfilter()); jfc.addChoosableFileFilter(newPNGfilter()); inti=jfc.showSaveDialog(this); if(i==JFileChooser.APPROVE_OPTION){ Filefile=jfc.getSelectedFile(); Stringabout="PNG"; Stringext=file.toString().toLowerCase(); javax.swing.filechooser.FileFilterff=jfc.getFileFilter(); if(ffinstanceofJPGfilter){ about="JPG"; if(!ext.endsWith(".jpg")){ Stringns=ext+".jpg"; file=newFile(ns); } }elseif(ffinstanceofPNGfilter){ about="PNG"; if(!ext.endsWith(".png")){ Stringns=ext+".png"; file=newFile(ns); } }elseif(ffinstanceofBMPfilter){ about="BMP"; if(!ext.endsWith(".bmp")){ Stringns=ext+".bmp"; file=newFile(ns); } }elseif(ffinstanceofGIFfilter){ about="GIF"; if(!ext.endsWith(".gif")){ Stringns=ext+".gif"; file=newFile(ns); } } if(ImageIO.write(get,about,file)){ JOptionPane.showMessageDialog(this,"保存成功!"); }else JOptionPane.showMessageDialog(this,"保存失败!"); } }catch(Exceptionexe){ exe.printStackTrace(); } } /** *公共的处理把当前的图片加入剪帖板的方法 */ publicvoiddoCopy(finalBufferedImageimage){ try{ if(get==null){ JOptionPane.showMessageDialog(this,"图片不能为空!!","错误",JOptionPane.ERROR_MESSAGE); return; } Transferabletrans=newTransferable(){ publicDataFlavor[]getTransferDataFlavors(){ returnnewDataFlavor[]{DataFlavor.imageFlavor}; } publicbooleanisDataFlavorSupported(DataFlavorflavor){ returnDataFlavor.imageFlavor.equals(flavor); } publicObjectgetTransferData(DataFlavorflavor)throwsUnsupportedFlavorException,IOException{ if(isDataFlavorSupported(flavor)) returnimage; thrownewUnsupportedFlavorException(flavor); } }; Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans,null); JOptionPane.showMessageDialog(this,"已复制到系统粘帖板!!"); }catch(Exceptionexe){ exe.printStackTrace(); JOptionPane.showMessageDialog(this,"复制到系统粘帖板出错!!","错误",JOptionPane.ERROR_MESSAGE); } } //处理关闭事件 privatevoiddoClose(Componentc){ jtp.remove(c); c=null; System.gc(); } publicvoidactionPerformed(ActionEventae){ Objectsource=ae.getSource(); if(source==start){ doStart(); }elseif(source==cancel){ System.exit(0); }elseif(source==java){ try{ UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(this); }catch(Exceptionexe){ exe.printStackTrace(); } }elseif(source==system){ try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(this); }catch(Exceptionexe){ exe.printStackTrace(); } }elseif(source==saveAll){ doSaveAll(); } } //一个内部类,它表示一个面板,一个可以被放进tabpane的面板 //也有自己的一套处理保存和复制的方法 privateclassPicPanelextendsJPanelimplementsActionListener{ JButtonsave,copy,close;//表示保存,复制,关闭的按钮 BufferedImageget;//得到的图片 publicPicPanel(BufferedImageget){ super(newBorderLayout()); this.get=get; initPanel(); } publicBufferedImagegetImage(){ returnget; } privatevoidinitPanel(){ save=newJButton("保存(S)"); copy=newJButton("复制到剪帖板(C)"); close=newJButton("关闭(X)"); save.setMnemonic('S'); copy.setMnemonic('C'); close.setMnemonic('X'); JPanelbuttonPanel=newJPanel(); buttonPanel.add(copy); buttonPanel.add(save); buttonPanel.add(close); JLabelicon=newJLabel(newImageIcon(get)); this.add(newJScrollPane(icon),BorderLayout.CENTER); this.add(buttonPanel,BorderLayout.SOUTH); save.addActionListener(this); copy.addActionListener(this); close.addActionListener(this); } publicvoidactionPerformed(ActionEvente){ Objectsource=e.getSource(); if(source==save){ doSave(get); }elseif(source==copy){ doCopy(get); }elseif(source==close){ get=null; doClose(this); } } } //保存BMP格式的过滤器 privateclassBMPfilterextendsjavax.swing.filechooser.FileFilter{ publicBMPfilter(){ } publicbooleanaccept(Filefile){ if(file.toString().toLowerCase().endsWith(".bmp")|| file.isDirectory()){ returntrue; }else returnfalse; } publicStringgetDescription(){ return"*.BMP(BMP图像)"; } } //保存JPG格式的过滤器 privateclassJPGfilterextendsjavax.swing.filechooser.FileFilter{ publicJPGfilter(){ } publicbooleanaccept(Filefile){ if(file.toString().toLowerCase().endsWith(".jpg")|| file.isDirectory()){ returntrue; }else returnfalse; } publicStringgetDescription(){ return"*.JPG(JPG图像)"; } } //保存GIF格式的过滤器 privateclassGIFfilterextendsjavax.swing.filechooser.FileFilter{ publicGIFfilter(){ } publicbooleanaccept(Filefile){ if(file.toString().toLowerCase().endsWith(".gif")|| file.isDirectory()){ returntrue; }else returnfalse; } publicStringgetDescription(){ return"*.GIF(GIF图像)"; } } //保存PNG格式的过滤器 privateclassPNGfilterextendsjavax.swing.filechooser.FileFilter{ publicbooleanaccept(Filefile){ if(file.toString().toLowerCase().endsWith(".png")|| file.isDirectory()){ returntrue; }else returnfalse; } publicStringgetDescription(){ return"*.PNG(PNG图像)"; } } //一个暂时类,用于显示当前的屏幕图像 privateclassTempextendsJPanelimplementsMouseListener,MouseMotionListener{ privateBufferedImagebi; privateintwidth,height; privateintstartX,startY,endX,endY,tempX,tempY; privateJFramejf; privateRectangleselect=newRectangle(0,0,0,0);//表示选中的区域 privateCursorcs=newCursor(Cursor.CROSSHAIR_CURSOR);//表示一般情况下的鼠标状态 privateStatescurrent=States.DEFAULT;//表示当前的编辑状态 privateRectangle[]rec;//表示八个编辑点的区域 //下面四个常量,分别表示谁是被选中的那条线上的端点 publicstaticfinalintSTART_X=1; publicstaticfinalintSTART_Y=2; publicstaticfinalintEND_X=3; publicstaticfinalintEND_Y=4; privateintcurrentX,currentY;//当前被选中的X和Y,只有这两个需要改变 privatePointp=newPoint();//当前鼠标移的地点 privatebooleanshowTip=true;//是否显示提示.如果鼠标左键一按,则提示不再显了 publicTemp(JFramejf,BufferedImagebi,intwidth,intheight){ this.jf=jf; this.bi=bi; this.width=width; this.height=height; this.addMouseListener(this); this.addMouseMotionListener(this); initRecs(); } privatevoidinitRecs(){ rec=newRectangle[8]; for(inti=0;i<rec.length;i++){ rec[i]=newRectangle(); } } publicvoidpaintComponent(Graphicsg){ g.drawImage(bi,0,0,width,height,this); g.setColor(Color.RED); g.drawLine(startX,startY,endX,startY); g.drawLine(startX,endY,endX,endY); g.drawLine(startX,startY,startX,endY); g.drawLine(endX,startY,endX,endY); intx=startX<endX?startX:endX; inty=startY<endY?startY:endY; select=newRectangle(x,y,Math.abs(endX-startX),Math.abs(endY-startY)); intx1=(startX+endX)/2; inty1=(startY+endY)/2; g.fillRect(x1-2,startY-2,5,5); g.fillRect(x1-2,endY-2,5,5); g.fillRect(startX-2,y1-2,5,5); g.fillRect(endX-2,y1-2,5,5); g.fillRect(startX-2,startY-2,5,5); g.fillRect(startX-2,endY-2,5,5); g.fillRect(endX-2,startY-2,5,5); g.fillRect(endX-2,endY-2,5,5); rec[0]=newRectangle(x-5,y-5,10,10); rec[1]=newRectangle(x1-5,y-5,10,10); rec[2]=newRectangle((startX>endX?startX:endX)-5,y-5,10,10); rec[3]=newRectangle((startX>endX?startX:endX)-5,y1-5,10,10); rec[4]=newRectangle((startX>endX?startX:endX)-5,(startY>endY?startY:endY)-5,10,10); rec[5]=newRectangle(x1-5,(startY>endY?startY:endY)-5,10,10); rec[6]=newRectangle(x-5,(startY>endY?startY:endY)-5,10,10); rec[7]=newRectangle(x-5,y1-5,10,10); if(showTip){ g.setColor(Color.CYAN); g.fillRect(p.x,p.y,170,20); g.setColor(Color.RED); g.drawRect(p.x,p.y,170,20); g.setColor(Color.BLACK); g.drawString("请按住鼠标左键不放选择截图区",p.x,p.y+15); } } //根据东南西北等八个方向决定选中的要修改的X和Y的座标 privatevoidinitSelect(Statesstate){ switch(state){ caseDEFAULT: currentX=0; currentY=0; break; caseEAST: currentX=(endX>startX?END_X:START_X); currentY=0; break; caseWEST: currentX=(endX>startX?START_X:END_X); currentY=0; break; caseNORTH: currentX=0; currentY=(startY>endY?END_Y:START_Y); break; caseSOUTH: currentX=0; currentY=(startY>endY?START_Y:END_Y); break; caseNORTH_EAST: currentY=(startY>endY?END_Y:START_Y); currentX=(endX>startX?END_X:START_X); break; caseNORTH_WEST: currentY=(startY>endY?END_Y:START_Y); currentX=(endX>startX?START_X:END_X); break; caseSOUTH_EAST: currentY=(startY>endY?START_Y:END_Y); currentX=(endX>startX?END_X:START_X); break; caseSOUTH_WEST: currentY=(startY>endY?START_Y:END_Y); currentX=(endX>startX?START_X:END_X); break; default: currentX=0; currentY=0; break; } } publicvoidmouseMoved(MouseEventme){ doMouseMoved(me); initSelect(current); if(showTip){ p=me.getPoint(); repaint(); } } //特意定义一个方法处理鼠标移动,是为了每次都能初始化一下所要选择的地区 privatevoiddoMouseMoved(MouseEventme){ if(select.contains(me.getPoint())){ this.setCursor(newCursor(Cursor.MOVE_CURSOR)); current=States.MOVE; }else{ States[]st=States.values(); for(inti=0;i<rec.length;i++){ if(rec[i].contains(me.getPoint())){ current=st[i]; this.setCursor(st[i].getCursor()); return; } } this.setCursor(cs); current=States.DEFAULT; } } publicvoidmouseExited(MouseEventme){ } publicvoidmouseEntered(MouseEventme){ } publicvoidmouseDragged(MouseEventme){ intx=me.getX(); inty=me.getY(); if(current==States.MOVE){ startX+=(x-tempX); startY+=(y-tempY); endX+=(x-tempX); endY+=(y-tempY); tempX=x; tempY=y; }elseif(current==States.EAST||current==States.WEST){ if(currentX==START_X){ startX+=(x-tempX); tempX=x; }else{ endX+=(x-tempX); tempX=x; } }elseif(current==States.NORTH||current==States.SOUTH){ if(currentY==START_Y){ startY+=(y-tempY); tempY=y; }else{ endY+=(y-tempY); tempY=y; } }elseif(current==States.NORTH_EAST||current==States.NORTH_EAST|| current==States.SOUTH_EAST||current==States.SOUTH_WEST){ if(currentY==START_Y){ startY+=(y-tempY); tempY=y; }else{ endY+=(y-tempY); tempY=y; } if(currentX==START_X){ startX+=(x-tempX); tempX=x; }else{ endX+=(x-tempX); tempX=x; } }else{ startX=tempX; startY=tempY; endX=me.getX(); endY=me.getY(); } this.repaint(); } publicvoidmousePressed(MouseEventme){ showTip=false; tempX=me.getX(); tempY=me.getY(); } publicvoidmouseReleased(MouseEventme){ if(me.isPopupTrigger()){ if(current==States.MOVE){ showTip=true; p=me.getPoint(); startX=0; startY=0; endX=0; endY=0; repaint(); }else{ jf.dispose(); updates(); } } } publicvoidmouseClicked(MouseEventme){ if(me.getClickCount()==2){ //Rectanglerec=newRectangle(startX,startY,Math.abs(endX-startX),Math.abs(endY-startY)); Pointp=me.getPoint(); if(select.contains(p)){ if(select.x+select.width<this.getWidth()&&select.y+select.height<this.getHeight()){ get=bi.getSubimage(select.x,select.y,select.width,select.height); jf.dispose(); updates(); }else{ intwid=select.width,het=select.height; if(select.x+select.width>=this.getWidth()){ wid=this.getWidth()-select.x; } if(select.y+select.height>=this.getHeight()){ het=this.getHeight()-select.y; } get=bi.getSubimage(select.x,select.y,wid,het); jf.dispose(); updates(); } } } } } publicstaticvoidmain(Stringargs[]){ SwingUtilities.invokeLater(newRunnable(){ publicvoidrun(){ newCaptureScreen(); } }); } } //一些表示状态的枚举 enumStates{ NORTH_WEST(newCursor(Cursor.NW_RESIZE_CURSOR)),//表示西北角 NORTH(newCursor(Cursor.N_RESIZE_CURSOR)), NORTH_EAST(newCursor(Cursor.NE_RESIZE_CURSOR)), EAST(newCursor(Cursor.E_RESIZE_CURSOR)), SOUTH_EAST(newCursor(Cursor.SE_RESIZE_CURSOR)), SOUTH(newCursor(Cursor.S_RESIZE_CURSOR)), SOUTH_WEST(newCursor(Cursor.SW_RESIZE_CURSOR)), WEST(newCursor(Cursor.W_RESIZE_CURSOR)), MOVE(newCursor(Cursor.MOVE_CURSOR)), DEFAULT(newCursor(Cursor.DEFAULT_CURSOR)); privateCursorcs; States(Cursorcs){ this.cs=cs; } publicCursorgetCursor(){ returncs; } }
希望本文所述对大家Java程序设计有所帮助。