将JFrame内容另存为.png =)

时间:2019-05-19 14:02:17

标签: java jframe screenshot

我需要某些帮助。我目前正在用Java开发2D游戏(我使用JFrame)。我想在按下某个按钮时保存框架的内容并将其存储在图像中。目前,我使用以下代码:

Robot robot = new Robot();
Rectangle screenSize = new Rectangle(display.getFrame().getX() + 3, display.getFrame().getY() + 26, handler.getWidth(), handler.getHeight());

BufferedImage screenShot = robot.createScreenCapture(screenSize);   ImageIO.write(screenShot,File("D:\\Programming\\First2DGame\\res\\textures\\Screenshot.png"));

问题在于,该操作需要截取屏幕一部分的屏幕截图 ,而不是边框​​本身的屏幕截图。这意味着,例如,如果我将窗口移动到屏幕的右下角,则收到不和谐的通知,然后按我的按钮,该通知将显示在屏幕截图中。 我已经搜索了一下,我尝试了这段代码:

 try
        {
            BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = image.createGraphics();
            frame.paint(graphics2D);
            ImageIO.write(image,"jpeg", new File("D:\\Programming\\First2DGame\\res\\textures\\Screenshot.png"));
        }
        catch(Exception e)
        {
            e.printStackTrace;
        }
    }

    protected void paintComponent(Graphics g)
    {
        g.drawRect(50,50,50,50);
    }

但是结果是一个白色的窗口: you can see it here

您也许知道如何创建仅仅框架的屏幕截图? 谢谢=)

ps:很抱歉,如果我犯了一些错误,我对stackOverflow:D还是比较陌生的

3 个答案:

答案 0 :(得分:1)

我认为您显示的示例代码非常正确...
您可以使用以下代码对其进行测试吗? :D 如果您删除了contentPane.printAll(g2d),如图所示,则只有白色窗口

public class ImageSaveTest extends JFrame {

    public static void main(String[] args) {
        new ImageSaveTest();
    }

    public ImageSaveTest() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        JPanel panel = new JPanel();
        panel.setPreferredSize(new Dimension(300, 300));
        panel.setLayout(new GridBagLayout());

        JLabel label = new JLabel("Hello! StackOverflow(Press Enter)");
        label.setFont(new Font("Default", Font.BOLD, 15));

        panel.add(label);
        add(panel);
        setVisible(true);
        pack();

        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                System.out.println(e.getKeyCode());
                if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                    try {
                        Container contentPane = getContentPane();
                        BufferedImage image = new BufferedImage(contentPane.getWidth(), contentPane.getHeight(),
                                BufferedImage.TYPE_INT_RGB);
                        Graphics2D g2d = image.createGraphics();
                        contentPane.printAll(g2d);
                        g2d.dispose();

                        // replace this path to your image
                        ImageIO.write(image, "jpeg", new File("Your Path/Print.png"));
                    } catch (IOException ex) {
                        // Exception Handling
                    }
                }
            }
        });
    }
}

答案 1 :(得分:0)

[更新](如果有人遇到相同的问题:3) 我做了一些研究,并且按照我的设想,解决方案是我应该通过重写JFrame上的paintComponent()方法来呈现所有内容(我想)。目前,我还真的不知道该怎么做,但是我认为我应该能够修复它。在接下来的几天里,我会很忙,但是我会告诉您什么时候才能开始工作! =)

答案 2 :(得分:0)

这是我的代码(我知道,这很长):


package dev.patatonzolo.first2Dgame;

import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import dev.patatonzolo.first2Dgame.display.Display;
import dev.patatonzolo.first2Dgame.gfx.Assets;
import dev.patatonzolo.first2Dgame.gfx.GameCamera;
import dev.patatonzolo.first2Dgame.playerInput.KeyManager;
import dev.patatonzolo.first2Dgame.playerInput.MouseInput;
import dev.patatonzolo.first2Dgame.ppes.GaussianBlur;
import dev.patatonzolo.first2Dgame.states.GameState;
import dev.patatonzolo.first2Dgame.states.IgMenuState;
import dev.patatonzolo.first2Dgame.states.MainMenuState;
import dev.patatonzolo.first2Dgame.states.OpeningState;
import dev.patatonzolo.first2Dgame.states.OptionsState;
import dev.patatonzolo.first2Dgame.states.QuitState;
import dev.patatonzolo.first2Dgame.states.State;

public class Game extends JPanel implements Runnable {

    private Display display;
    private int width;
    private int height;
    public String title;
    protected int ticks = 0;

    private Thread thread;

    private boolean running = false;
    private BufferStrategy bufferStrategy;
    private Graphics2D graphics2d;

    public State gameState;
    public State openingState;
    public State igMenuState;
    public State mainMenuState;
    public State optionsState;
    public State quitState;

    private KeyManager keyManager;
    private MouseInput mouseInput;

    private GameCamera gameCamera;

    private Handler handler;


    public Game(String title, int width, int height) {
        this.width = width;
        this.height = height;
        this.title = title;
        keyManager = new KeyManager();
        mouseInput = new MouseInput();
    }

    private void takeScreenshot() {
        try {
        Container contentPane = display.getFrame().getContentPane();
        BufferedImage image = new BufferedImage(contentPane.getWidth(), contentPane.getHeight(),
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();
        contentPane.printAll(g2d);
        g2d.dispose();

        ImageIO.write(image, "png", new File("C:\\Users\\VgRig\\eclipse-workspace\\First2DGame\\res\\textures\\screenshot.png"));
    } catch (IOException e) {
        e.printStackTrace();
        }
    }

    @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D)g;

      }

    private void init() {
        display = new Display(title, width, height);
        display.getFrame().addKeyListener(keyManager);
        display.getFrame().addMouseListener(mouseInput);
        display.getFrame().addMouseMotionListener(mouseInput);
        display.getCanvas().addMouseListener(mouseInput);
        display.getCanvas().addMouseMotionListener(mouseInput);
        Assets.init();

        handler = new Handler(this);
        gameCamera = new GameCamera(handler, 0, 0);
        gameState = new GameState(handler);
        openingState = new OpeningState(handler);
        igMenuState = new IgMenuState(handler);
        mainMenuState = new MainMenuState(handler);
        optionsState = new OptionsState(handler);
        quitState = new QuitState(handler);
        State.setState(gameState);

    }

    public void update() {
        keyManager.update();
        mouseInput.update();
        if(State.getState() != null) {
            State.getState().update();
        }

        if(handler.getKeyManager().right) {
        }

        // MENUS 
        if(handler.getKeyManager().menu) {
            takeScreenshot();
            //GaussianBlur.Blur();
            State.setState(igMenuState);
        }
        if(State.getState() == gameState && handler.getKeyManager().menu) {
            State.setState(gameState);
        }

        if(State.getState() != igMenuState) {
            IgMenuState.currentSelection = 4;
        }
        if(State.getState() != quitState) {
            QuitState.currentSelection = 2;
        }

    }

    private void render() {
        bufferStrategy = display.getCanvas().getBufferStrategy();
        if(bufferStrategy == null) {
            display.getCanvas().createBufferStrategy(3);
            return;
        }
        graphics2d = (Graphics2D) bufferStrategy.getDrawGraphics();
        graphics2d.clearRect(0, 0, width, height);

        if(State.getState() != null) {
            State.getState().render(graphics2d);
        }

        bufferStrategy.show();
        graphics2d.dispose();

    }

    public void run() { 
        init();

        int fps = 60;
        double timePerTick = 1000000000 / fps;
        double delta = 0;
        long now;
        long lastTime = System.nanoTime();
        long framePerSecond = 0;

        while(running) {
            now = System.nanoTime();
            delta += (now - lastTime) / timePerTick;
            framePerSecond += now - lastTime;
            lastTime = now;

            if(delta >= 1) {
                update();
                render();
                ticks ++;
                delta --;
            }

            if(framePerSecond >= 1000000000) {
                System.out.println("Game running at [" + ticks + " FPS]");
                ticks = 0;
                framePerSecond = 0;
            }
        }       

        stop();
    }

    public int getTicks() {
        return ticks;
    }

    public void setTicks(int ticks) {
        this.ticks = ticks;
    }

    public KeyManager getKeyManager() {
        return keyManager;
    }

    public MouseInput getMouseInput() {
        return mouseInput;
    }

    public GameCamera getGameCamera() {
        return gameCamera;
    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }

    public synchronized void start() {
        if(running)
            return;
        running = true;
        thread = new Thread(this);
        thread.start();
    }

    public synchronized void stop() {
        if(running = false)
            return;
        running = false;
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}