




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
第Java實(shí)現(xiàn)屏幕截圖工具的代碼分享目錄效果展示程序結(jié)構(gòu)核心代碼
效果展示
程序運(yùn)行后的截圖:
先測(cè)試一下功能:
截圖過(guò)程對(duì)界面的捕捉:
雙擊保存后的顯示界面:
后續(xù)的步驟就自己去嘗試吧,這里給出了簡(jiǎn)單的測(cè)試過(guò)程。
程序結(jié)構(gòu)
核心代碼
CaptureScreen.java類
/**
*CaptureScreen.java
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;
privateJPanelc;
privateBufferedImageget;
privateJTabbedPanejtp;//一個(gè)放置很多份圖片
privateintindex;//一個(gè)一直會(huì)遞增的索引,用于標(biāo)認(rèn)圖片
privateJRadioButtonjava,system;//JAVA界面,系統(tǒng)界面
/**CreatesanewinstanceofCaptureScreen*/
publicCaptureScreen(){
super("屏幕截取");
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exceptionexe){
exe.printStackTrace();
initWindow();
initOther();
privatevoidinitOther(){
jtp=newJTabbedPane(JTabbedPane.TOP,JTabbedPane.SCROLL_TAB_LAYOUT);
privatevoidinitWindow(){
start=newJButton("開(kāi)始截取");
cancel=newJButton("退出");
start.addActionListener(this);
cancel.addActionListener(this);
JPanelbuttonJP=newJPanel();
c=newJPanel(newBorderLayout());
JLabeljl=newJLabel("屏幕截取",JLabel.CENTER);
jl.setFont(newFont("黑體",Font.BOLD,40));
jl.setForeground(Color.RED);
c.add(jl,BorderLayout.CENTER);
buttonJP.add(start);
buttonJP.add(cancel);
buttonJP.setBorder(BorderFactory.createTitledBorder("公共操作區(qū)"));
JPaneljp=newJPanel();//放置兩個(gè)單選按鈕的面板
jp.add(java=newJRadioButton("java界面"));
jp.add(system=newJRadioButton("系統(tǒng)界面",true));
java.addActionListener(this);
system.addActionListener(this);
jp.setBorder(BorderFactory.createTitledBorder("界面風(fēng)格"));
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.EXIT_ON_CLOSE);
privatevoidupdates(){
this.setVisible(true);
if(get!=null){
//如果索引是0,則表示一張圖片都沒(méi)有被加入過(guò),
//則要清除當(dāng)前的東西,重新把tabpane放進(jìn)來(lái)
if(index==0){
c.removeAll();
c.add(jtp,BorderLayout.CENTER);
}else{//否則的話,直接對(duì)tabpane添加面板就可以了
//就什么都不用做了
PicPanelpic=newPicPanel(get);
jtp.addTab("圖片"+(++index),pic);
jtp.setSelectedComponent(pic);
SwingUtilities.updateComponentTreeUI(c);//調(diào)整LookAndFeel(javax.swing)
privatevoiddoStart(){
try{
this.setVisible(false);
Thread.sleep(500);//睡500毫秒是為了讓主窗完全不見(jiàn)
Robotro=newRobot();//(通過(guò)本地操作)控制鼠標(biāo)、鍵盤(pán)等實(shí)際輸入源(java.awt)
Toolkittk=Toolkit.getDefaultToolkit();//AWT組件的抽象父類(java.awt)
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);//自定義的Temp類的對(duì)象
jf.getContentPane().add(temp,BorderLayout.CENTER);
jf.setUndecorated(true);
jf.setSize(di);
jf.setVisible(true);
jf.setAlwaysOnTop(true);
}catch(Exceptionexe){
exe.printStackTrace();
*公用的處理保存圖片的方法
publicvoiddoSave(BufferedImageget){
try{
if(get==null){
JOptionPane.showMessageDialog(this
,"圖片不能為空!!","錯(cuò)誤",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){
if(!ext.endsWith(".jpg")){
Stringns=ext+".jpg";
file=newFile(ns);
about="JPG";
}elseif(ffinstanceofPNGfilter){
if(!ext.endsWith(".png")){
Stringns=ext+".png";
file=newFile(ns);
about="PNG";
}elseif(ffinstanceofBMPfilter){
if(!ext.endsWith(".bmp")){
Stringns=ext+".bmp";
file=newFile(ns);
about="BMP";
}elseif(ffinstanceofGIFfilter){
if(!ext.endsWith(".gif")){
Stringns=ext+".gif";
file=newFile(ns);
about="GIF";
if(ImageIO.write(get,about,file)){
JOptionPane.showMessageDialog(this,"保存成功!");
}else
JOptionPane.showMessageDialog(this,"保存失?。?);
}catch(Exceptionexe){
exe.printStackTrace();
/**
*公共的處理把當(dāng)前的圖片加入剪帖板的方法
publicvoiddoCopy(finalBufferedImageimage){
try{
if(get==null){
JOptionPane.showMessageDialog(this
,"圖片不能為空!!","錯(cuò)誤",JOptionPane.ERROR_MESSAGE);
return;
}//java.awt.datatransfer(接口)
Transferabletrans=newTransferable(){//內(nèi)部類
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,"已復(fù)制到系統(tǒng)粘帖板!!");
}catch(Exceptionexe){
exe.printStackTrace();
JOptionPane.showMessageDialog(this
,"復(fù)制到系統(tǒng)粘帖板出錯(cuò)!!","錯(cuò)誤",JOptionPane.ERROR_MESSAGE);
//處理關(guān)閉事件
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();
//一個(gè)內(nèi)部類,它表示一個(gè)面板,一個(gè)可以被放進(jìn)tabpane的面板
//也有自己的一套處理保存和復(fù)制的方法
privateclassPicPanelextendsJPanelimplementsActionListener{
JButtonsave,copy,close;//表示保存,復(fù)制,關(guān)閉的按鈕
BufferedImageget;//得到的圖片
publicPicPanel(BufferedImageget){
super(newBorderLayout());
this.get=get;
initPanel();
privatevoidinitPanel(){
save=newJButton("保存(S)");
copy=newJButton("復(fù)制到剪帖板(C)");
close=newJButton("關(guān)閉(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格式的過(guò)濾器
privateclassBMPfilterextendsjavax.swing.filechooser.FileFilter{
publicBMPfilter(){
publicbooleanaccept(Filefile){
if(file.toString().toLowerCase().endsWith(".bmp")||
file.isDirectory()){
returntrue;
}else
returnfalse;
publicStringgetDescription(){
return"*.BMP(BMP圖像)";
//保存JPG格式的過(guò)濾器
privateclassJPGfilterextendsjavax.swing.filechooser.FileFilter{
publicJPGfilter(){
publicbooleanaccept(Filefile){
if(file.toString().toLowerCase().endsWith(".jpg")||
file.isDirectory()){
returntrue;
}else
returnfalse;
publicStringgetDescription(){
return"*.JPG(JPG圖像)";
//保存GIF格式的過(guò)濾器
privateclassGIFfilterextendsjavax.swing.filechooser.FileFilter{
publicGIFfilter(){
publicbooleanaccept(Filefile){
if(file.toString().toLowerCase().endsWith(".gif")||
file.isDirectory()){
returntrue;
}else
returnfalse;
publicStringgetDescription(){
return"*.GIF(GIF圖像)";
//保存PNG格式的過(guò)濾器
privateclassPNGfilterextendsjavax.swing.filechooser.FileFilter{
publicbooleanaccept(Filefile){
if(file.toString().toLowerCase().endsWith(".png")||
file.isDirectory()){
returntrue;
}else
returnfalse;
publicStringgetDescription(){
return"*.PNG(PNG圖像)";
//一個(gè)臨時(shí)類,用于顯示當(dāng)前的屏幕圖像
privateclassTempextendsJPanelimplementsMouseListener,MouseMotionListener{
privateBufferedImagebi;
privateintwidth,height;
privateintstartX,startY,endX,endY,tempX,tempY;
privateJFramejf;
privateRectangleselect=newRectangle(0,0,0,0);//表示選中的區(qū)域
privateCursorcs=newCursor(Cursor.CROSSHAIR_CURSOR);//表示一般情況下的鼠標(biāo)狀態(tài)(十字線)
privateStatescurrent=States.DEFAULT;//表示當(dāng)前的編輯狀態(tài)
privateRectangle[]rec;//表示八個(gè)編輯點(diǎn)的區(qū)域
//下面四個(gè)常量,分別表示誰(shuí)是被選中的那條線上的端點(diǎn)
publicstaticfinalintSTART_X=1;
publicstaticfinalintSTART_Y=2;
publicstaticfinalintEND_X=3;
publicstaticfinalintEND_Y=4;
privateintcurrentX,currentY;//當(dāng)前被選中的X和Y,只有這兩個(gè)需要改變
privatePointp=newPoint();//當(dāng)前鼠標(biāo)移的地點(diǎn)
privatebooleanshowTip=true;//是否顯示提示.如果鼠標(biāo)左鍵一按,則提示就不再顯示了
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;irec.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=startXendXstartX:endX;
inty=startYendYstartY: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((startXendXstartX:endX)-5,y-5,10,10);
rec[3]=newRectangle((startXendXstartX:endX)-5,y1-5,10,10);
rec[4]=newRectangle((startXendXstartX:endX)-5,(startYendYstartY:endY)-5,10,10);
rec[5]=newRectangle(x1-5,(startYendYstartY:endY)-5,10,10);
rec[6]=newRectangle(x-5,(startYendYstartY: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("請(qǐng)按住鼠標(biāo)左鍵不放選擇截圖區(qū)",p.x,p.y+15);
//根據(jù)東南西北等八個(gè)方向決定選中的要修改的X和Y的座標(biāo)
privatevoidinitSelect(Statesstate){
switch(state){
caseDEFAULT:
currentX=0;
currentY=0;
break;
caseEAST:
currentX=(endXstartXEND_X:START_X);
currentY=0;
break;
caseWEST:
currentX=(endXstartXSTART_X:END_X);
currentY=0;
break;
caseNORTH:
currentX=0;
currentY=(startYendYEND_Y:START_Y);
break;
caseSOUTH:
currentX=0;
currentY=(startYendYSTART_Y:END_Y);
break;
caseNORTH_EAST:
currentY=(startYendYEND_Y:START_Y);
currentX=(endXstartXEND_X:START_X);
break;
caseNORTH_WEST:
currentY=(startYendYEND_Y:START_Y);
currentX=(endXstartXSTART_X:END_X);
break;
caseSOUTH_EAST:
currentY=(startYendYSTART_Y:END_Y);
currentX=(endXstartXEND_X:START_X);
break;
caseSOUTH_WEST:
currentY=(startYendYSTART_Y:END_Y);
currentX=(endXstartXSTART_X:END_X);
break;
default:
currentX=0;
currentY=0;
break;
publicvoidmouseMoved(MouseEventme){
doMouseMoved(me);
initSelect(current);//current:當(dāng)前狀態(tài)(state)
if(showTip){
p=me.getPoint();
repaint();
//特意定義一個(gè)方法處理鼠標(biāo)移動(dòng),是為了每次都能初始化一下所要選擇的區(qū)域
privatevoiddoMouseMoved(MouseEventme){
if(select.contains(me.getPoint())){
this.setCursor(newCursor(Cursor.MOVE_CURSOR));
current=States.MOVE;
}else{
States[]st=States.values();
for(inti=0;irec.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();
//分別處理一系列的(光標(biāo))狀態(tài)(枚舉值)
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();
sta
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 軟件測(cè)試工程師能力構(gòu)建試題及答案
- 新興領(lǐng)域中的領(lǐng)導(dǎo)力重要性研究試題及答案
- 計(jì)算機(jī)四級(jí)多領(lǐng)域試題及答案探討
- 2025年電動(dòng)汽車電池?zé)峁芾砑夹g(shù)環(huán)保性與可持續(xù)性分析報(bào)告
- 污水處理廠新建工程項(xiàng)目運(yùn)營(yíng)管理方案
- 工業(yè)互聯(lián)網(wǎng)NFV平臺(tái)在智能工廠生產(chǎn)設(shè)備運(yùn)行效率提升中的應(yīng)用報(bào)告
- 2025年廢舊電子產(chǎn)品無(wú)害化處理與資源回收行業(yè)市場(chǎng)動(dòng)態(tài)與競(jìng)爭(zhēng)格局研究報(bào)告
- 2025年借用人員勞動(dòng)合同范本
- C語(yǔ)言解決方案試題及答案
- 軟件測(cè)試課程考試重點(diǎn)試題及答案
- 安徽省六安市2024-2025學(xué)年八年級(jí)(下)期中歷史試卷(含答案)
- 航運(yùn)業(yè)人力資源開(kāi)發(fā)與管理考核試卷
- 福建省三明市2025年普通高中高三畢業(yè)班五月質(zhì)量檢測(cè)物理試卷及答案(三明四檢)
- 7.1 觀察物體(課件)-2024-2025學(xué)年蘇教版數(shù)學(xué)一年級(jí)下冊(cè)
- 早產(chǎn)兒試題及答案多選
- 2025年上海市靜安區(qū)初三二模語(yǔ)文試卷(含答案)
- 2025年公共安全管理考試題及答案
- 2025年寧夏吳忠紅寺堡區(qū)公開(kāi)招聘社區(qū)工作者46人筆試備考題庫(kù)及答案解析
- 搶救配合流程和站位規(guī)范
- 2025年高考物理考試易錯(cuò)題易錯(cuò)點(diǎn)07動(dòng)量定理、動(dòng)量守恒定律(3陷阱點(diǎn)7考點(diǎn)4題型)(學(xué)生版+解析)
- 雨季行車安全教育
評(píng)論
0/150
提交評(píng)論