java保存JFrame窗口的内容为图片

原文链接:https://stackoverflow.com/questions/12575201/how-to-save-a-image-on-jframe

考虑到截图保存窗口如果被其他置顶窗口挡住,或者窗口在屏幕外的话无效了,所以采用如下方法。


	public void savePic(JFrame jf){
		//得到窗口内容面板
		Container content=jf.getContentPane();
		//创建缓冲图片对象
		BufferedImage img=new BufferedImage(
				jf.getWidth(),jf.getHeight(),BufferedImage.TYPE_INT_RGB);
		//得到图形对象
		Graphics2D g2d = img.createGraphics();
		//将窗口内容面板输出到图形对象中
		content.printAll(g2d);
		//保存为图片
		File f=new File("saveScreen.jpg");
		try {
			ImageIO.write(img, "jpg", f);
		} catch (IOException e) {
			e.printStackTrace();
		}
		//释放图形对象
		g2d.dispose();
	}





  • 6
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要在Java JFrame窗口中添加背景图片,可以使用以下步骤: 1. 将图片文件保存在项目文件夹中。 2. 在JFrame类中创建一个JPanel对象来包含所有的组件。 3. 创建一个ImageIcon对象,将其设置为JPanel的背景。 4. 将JPanel对象添加到JFrame中。 5. 调用JFrame的pack()方法来自动调整大小。 以下是一个简单的示例代码: ```java import javax.swing.*; import java.awt.*; public class JFrameWithBackground extends JFrame { public JFrameWithBackground() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 500, 500); // Create a JPanel to contain all components JPanel contentPane = new JPanel(); setContentPane(contentPane); contentPane.setLayout(null); // Load the background image ImageIcon backgroundImage = new ImageIcon("background.jpg"); // Set the background image as the JPanel's background JLabel backgroundLabel = new JLabel(backgroundImage); backgroundLabel.setBounds(0, 0, backgroundImage.getIconWidth(), backgroundImage.getIconHeight()); contentPane.add(backgroundLabel); // Add other components to the JPanel // ... // Pack and display the JFrame pack(); setVisible(true); } public static void main(String[] args) { new JFrameWithBackground(); } } ``` 在这个示例中,我们创建了一个JFrameWithBackground类,继承自JFrame。在构造函数中,我们首先设置了JFrame的默认关闭操作和大小。然后,我们创建了一个JPanel对象,并将其设置为JFrame内容面板。我们使用null布局,以便我们可以自由地定位组件。 接下来,我们加载了背景图片,并将其设置为JPanel的背景。我们创建了一个JLabel对象来显示该图像,并将其添加到JPanel中。我们还可以添加其他组件到JPanel中。 最后,我们调用JFrame的pack()方法来自动调整大小,使所有组件都可以适应窗口大小,并使JFrame可见。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值