Is there a way to take a screenshot using Java and save it to some sort of image?

后端 未结 8 815
盖世英雄少女心
盖世英雄少女心 2020-11-22 06:19

Simple as the title states: Can you use only Java commands to take a screenshot and save it? Or, do I need to use an OS specific program to take the screenshot and then gra

8条回答
  •  一整个雨季
    2020-11-22 07:16

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Rectangle;
    import java.awt.Robot;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.io.File; 
    import javax.imageio.ImageIO;
    import javax.swing.*;  
    
    public class HelloWorldFrame extends JFrame implements ActionListener {
    
    JButton b;
    public HelloWorldFrame() {
        this.setVisible(true);
        this.setLayout(null);
        b = new JButton("Click Here");
        b.setBounds(380, 290, 120, 60);
        b.setBackground(Color.red);
        b.setVisible(true);
        b.addActionListener(this);
        add(b);
        setSize(1000, 700);
    }
    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == b) 
        {
            this.dispose();
            try {
                Thread.sleep(1000);
                Toolkit tk = Toolkit.getDefaultToolkit(); 
                Dimension d = tk.getScreenSize();
                Rectangle rec = new Rectangle(0, 0, d.width, d.height);  
                Robot ro = new Robot();
                BufferedImage img = ro.createScreenCapture(rec);
                File f = new File("myimage.jpg");//set appropriate path
                ImageIO.write(img, "jpg", f);
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
        }
    }
    
    public static void main(String[] args) {
        HelloWorldFrame obj = new HelloWorldFrame();
    }
    }
    

提交回复
热议问题