简体   繁体   中英

How to create a Rectangle with the default x and y values at the top-left corner of the content pane, not the screen

I'm adding a function in my game that takes a screenshot and saves it to a new image. I have no problems with the filepath or anything of that sort, but rather the Rectangle through which the screenshot is taken. If I make a new Rectangle , like such:

new Rectangle(0, 0, 500, 500);

then it creates a 500 x 500 Rectangle at the top left of the computer screen, not at the top left of the content pane. The content pane to which I am referring is much smaller than the screen and located in the center. Thanks for reading, any help would be appreciated.

For any component (which can be a JPanel , Container , Window , or basically anything), you can use this to get the Rectangle that will represent its bounds on the screen:

Rectangle getBoundsOnScreen( Component component ) {
    Point topLeft = component.getLocationOnScreen();
    Dimension size = component.getSize();
    return new Rectangle( topLeft, size );
}

So if you wanted just the content pane of a JFrame :

getBoundsOnScreen( frame.getContentPane() );

For stuff like an entire JFrame , you can just do this:

frame.getBounds();

Look at the example below. I first create a RectangleComponent class, which extends the Rectangle class:

import javax.swing.*;
import java.awt.*;

public class RectangleComponent extends JComponent
{
 Rectangle rectangle;

 public RectangleComponent(int xspace,int yspace, int width, int height)
{
    rectangle  = new Rectangle(xspace, yspace, width, height);
}

public void paintComponent(Graphics g)
{
    Graphics2D g2 = (Graphics2D) g;
    g2.draw(rectangle);
}
}

Now we create a class that generates the main window, where you add the Rectangle component:

import javax.swing.*;
import java.awt.*;

public class CustomComponent extends JFrame {

private static final long serialVersionUID = 1L;

public CustomComponent() {

}

public static void main(String[] args) {
    JFrame frame = new JFrame("Java Rulez");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(100,100,600,600);
    frame.getContentPane().setBackground(Color.YELLOW);

    frame.add(new RectangleComponent(0, 0, 500, 500));

    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM