如何将计算机上保存的jpg添加到我编写的代码中

问题描述 投票:0回答:2

这是一个旨在看起来像Windows 10蓝屏死机的Java程序,但我不知道如何向其中添加图像。我尝试了许多不同的方法,但是它们对我没有用,也许我做错了。图像是将位于左下角的QR码。

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

public class BSODJava {
 public static void main(String[] args) {
  JFrame frame = new JFrame("Lab00");
  frame.setSize(1366, 768);
  frame.setLocation(0, 0);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setContentPane(new Panel1());
  frame.setVisible(true);
  frame.setBackground(Color.black);
 }
}
class Panel1 extends JPanel {
 public void paintComponent(Graphics g) {
  g.setColor(new Color(6, 117, 170));
  g.fillRect(1, 1, 1366, 768);

  g.setColor(new Color(255, 255, 255));
  g.setFont(new Font("Segoe UI", Font.PLAIN, 200));
  g.drawString(";)", 50, 165);

  g.setColor(new Color(255, 255, 255));
  g.setFont(new Font("Segoe UI", Font.PLAIN, 52));
  g.drawString("Your PC ran into a problem and needs to restart.  We'll", 50, 270);

  g.setColor(new Color(255, 255, 255));
  g.setFont(new Font("Segoe UI", Font.PLAIN, 52));
  g.drawString("restart for you.", 50, 330);
 }
}
java swing graphics awt
2个回答
1
投票

无需进行所有自定义绘画。 Swing具有为您完成绘画的组件。

使用JLabel开始。您可以显示带有文字和/或图标的JLabel。阅读Swing教程中有关How to Use Icons的部分,以获取入门的示例。

然后还将学习如何使用Layout Managers将组件放置在面板上。


0
投票

在您的main中(或如果您在初始化帧时在某处使用camickr的Swing解决方案),请加载图像。有点像这样:

 BufferedImage image;

 // somewhere in your constructor for example
 this.image = ImageIO.read(new File("/Path/To/My/Picture/some-picture.jpg"));

如果要在资源文件夹中的应用程序中包含图片,则应将其复制到应用程序(like I showed in this answer)

现在,当您加载图像并调用paintComponent方法时,可以向其提供如何以及在何处绘制它的信息:

public void paintComponent(Graphics g) 
{ 
  // ... your code
  g.setColor(new Color(255, 255, 255)); 
  g.setFont(new Font("Segoe UI",Font.PLAIN, 52)); 
  g.drawString("restart for you.", 50, 330);     

  g.drawImage(this.image, 0,0,null);  // this will draw the image in the top left corner (keeping it's aspect ration, width and height)

  g.drawImage(                        // to draw the image in the bottom right corner
     this.image,                      // your image instance
     getWidth() - image.getWidth(),   // the frame's width minus the image's width
     getHeight() - image.getHeight(), // and the frame's height minus the image's height
     null                             // no need for an image observer
  );      
}

当然,您可以对图像做更多的事情,并根据需要进行操作。也许this tutorials from MKyong可以帮助您读取和写入图像。

© www.soinside.com 2019 - 2024. All rights reserved.