[英]How to create a Rectangle with the default x and y values at the top-left corner of the content pane, not the screen
我在游戏中添加了一个功能,该功能可以截取屏幕截图并将其保存到新图像中。 我的文件路径或类似的东西都没有问题,但是截图是通过Rectangle
进行的。 如果我创建一个新的Rectangle
,例如:
new Rectangle(0, 0, 500, 500);
那么它将在计算机屏幕的左上方而不是内容窗格的左上方创建一个500 x 500的Rectangle
。 我要引用的内容窗格比屏幕小得多,并且位于中间。 感谢您的阅读,任何帮助将不胜感激。
对于任何组件(可以是JPanel
, Container
, Window
或基本上任何东西),都可以使用它来获取Rectangle
,该Rectangle
将在屏幕上表示其边界:
Rectangle getBoundsOnScreen( Component component ) {
Point topLeft = component.getLocationOnScreen();
Dimension size = component.getSize();
return new Rectangle( topLeft, size );
}
因此,如果只需要JFrame
的内容窗格:
getBoundsOnScreen( frame.getContentPane() );
对于整个JFrame
类的东西,您可以执行以下操作:
frame.getBounds();
看下面的例子。 我首先创建一个RectangleComponent类,它扩展了Rectangle类:
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);
}
}
现在,我们创建一个生成主窗口的类,在其中添加Rectangle组件:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.