绘制窗体,获取图片并截图

package ui;
import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JFrame;

public class FrameGame extends JFrame{
    public FrameGame() {
        //窗口标题
        this.setTitle("java");
        //设置窗口大小
        setSize(1200,600);
        //显示窗体
        setVisible(true);
        //设计默认关闭属性(程序结束)
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        //不允许改变窗口大小
        this.setResizable(false);
        // 居中
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        // Dimension类的高度和宽度值是一个整数,表明有多少个像素点
        Dimension screen = toolkit.getScreenSize();
        // 绘制窗体与屏幕的左边距
        int x = (screen.width - this.getWidth()) / 2;
        // 绘制窗体与屏幕的上边距
        int y = (screen.height - this.getHeight()) / 2 - 8;
        // 将窗体放置在所设的(x,y)坐标处
        this.setLocation(x, y);
        // 把JPanelGame方法设置成为frame的内容面板
        this.setContentPane(new PanelGame());
    }
}
package ui;

import java.awt.Graphics;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class PanelGame extends JPanel {
    public PanelGame() {
        
    }
    public void paintComponent(Graphics g) {
        //获取图片
        Image img = new ImageIcon("graphics/background/bg01.jpg").getImage();
        //将截取图片放在指定位置
        //(一共有四组坐标,第一二组分别是窗体左上和右下坐标,第三四组是截取图片的左上和右下坐标)
        g.drawImage(img,400,50,800,550,500,350,900,850, null);
    }
}
package main;

import ui.FrameGame;

public class Main {
    public static void main(String[] args) {
        new FrameGame();
    }
    
}
原文地址:https://www.cnblogs.com/xiaoyqng/p/8487502.html