[英]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.