这是一个Java程序,旨在看起来像Windows 10蓝屏死机,但我无法弄清楚如何向其添加图像。
我尝试了许多不同的方法,但它们对我不起作用,也许我做错了。图像是将位于左下角的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);
}
}
没有必要做所有的自定义绘画。Swing 有组件可以为您完成绘画。
首先使用JLabel
.您可以显示带有文本和/或图标的JLabel
。阅读 Swing 教程中有关如何使用图标的部分,以获取入门示例。
然后,还要了解如何使用布局管理器在面板上定位组件。
在您的main
中(或者如果您在初始化帧时在某处使用 camickr 的 Swing 解决方案(,您可以加载图像。有点像这样:
BufferedImage image;
// somewhere in your constructor for example
this.image = ImageIO.read(new File("/Path/To/My/Picture/some-picture.jpg"));
如果要将图片放在 resources 文件夹中的应用程序中,则应将其复制到应用程序中(如我在此答案中所示(。
现在,当您加载图像并调用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
);
}
当然,您可以对图像执行更多操作,并根据需要对其进行操作。也许MKyong的本教程可以帮助您读取和写入图像。