Search code examples
javainputborderscreenshot

Questions on how to do certain actions when taking a screenshot


So in my java project I made some code for the a screenshot feature

now this is the code that I have made

public void takeScreenshot() {
        try {
            Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
            Point point = window.getLocationOnScreen();
            int x = (int)point.getX();
            int y = (int)point.getY();
            int w = window.getWidth();
            int h = window.getHeight();
            Robot robot = new Robot(window.getGraphicsConfiguration().getDevice());
            Rectangle captureSize = new Rectangle(x, y, w, h);
            java.awt.image.BufferedImage bufferedimage = robot.createScreenCapture(captureSize);
            int picNumber = random(100);
            String fileExtension = "The Iron Door";
            File file = new File((new StringBuilder()).append(SignLink.getCacheDirectory() + "Screenshots/" + fileExtension + " ").append(picNumber).append(".png").toString());
            ImageIO.write(bufferedimage, "png", file);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

now that code works perfectly I have it set up to do the action on the hotkey now I have two questions

1) how would I add some kind of a border around it which is pre-made by me and when the user takes the screenshot it puts the border on the image

2) how would I make it so the user can input the name they want the screenshot to be called


Solution

  • how would I make it so the user can input the name they want the screenshot to be called

    Take a look at JFileChooser

    how would I add some kind of a border around it which is pre-made by me and when the user takes the screenshot it puts the border on the image

    This is a little more involved and will depend on what you want to achieve.

    Start by creating a new BufferedImage which is the same size as the screenshot with the border size added to it...

     BufferedImage img = new BufferedImage(bufferedimage.getWidth() + borderSize, bufferedimage.getWidth() + borderSize, BufferedImage.TYPE_INT_RGB);
    

    Get a Graphics context from the new BufferedImage...

    Graphics2D g2d = img.createGraphics();
    

    Paint the screenshot to it...

    g2d.drawImage(bufferedimage, borderSize / 2, borderSize / 2, null);
    

    Paint the border and dispose of the graphics context

    g2d.dispose();
    

    Depending on what you want to achieve, you could paint the border first and paint the image second, but that's up to you