Home > Java > javaTutorial > How to write a screenshot gadget in Java?

How to write a screenshot gadget in Java?

王林
Release: 2023-05-08 23:10:06
forward
1779 people have browsed it

效果展示

How to write a screenshot gadget in Java?

代码展示

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class PrintScreen extends JFrame{
    PrintScreen(){
        this.setTitle("Java屏幕截图小工具");
        this.setSize(400,300);
        this.setVisible(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        JButton jButton=new JButton("点击截图");
        jButton.setSize(120,60);
        setLayout(new FlowLayout());
        getContentPane().add(jButton);
        //为按钮添加监听事件
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    PrintScreen();
                } catch (AWTException | IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
    }
    
	//实现截图功能
    public static void PrintScreen() throws AWTException, IOException {
        Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
        int width=(int)screenSize.getWidth();
        int height=(int)screenSize.getHeight();
        Robot robot=new Robot();
        BufferedImage bi=robot.createScreenCapture(new Rectangle(width,height));
        ImageIO.write(bi,"png",new File("C:\\Users\\Administrator\\Desktop","上一张截图.png"));
    }
    public static void main(String[] args){
        PrintScreen printScreen=new PrintScreen();
    }
}
Copy after login

项目结构

本程序用于初学者学习,结构简单,所有功能在主类中实现。

How to write a screenshot gadget in Java?

设计思路

首先绘制窗口,添加按钮组件,然后为按钮添加监听事件,实现截图功能。新的截图放在桌面,并命名为上一张截图.png。此路径可以根据自己的需求更改。

本程序中异常处理和事件处理是重点,也是Java进阶学习的重要部分,虽然GUI现在并没有很大的市场,甚至很多Java初学者放弃学习GUI技术,但是利用GUI编程的过程对于培养编程兴趣,深入理解Java编程有很大的作用。

本程序还可以进行优化,用于截取不同形状的截图,满足用户的需求。通过添加坐标变量来截取屏幕上所需要的像素点。同时,还可以对这个简易的窗口进行美化。本程序是一个学习Java编程的练手好项目。

项目测试

How to write a screenshot gadget in Java?

运行程序,点击截图按钮,在目标文件路径下生成一个命名为“上一张截图.png”的文件,如上图。

The above is the detailed content of How to write a screenshot gadget in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template