您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在Java的Swing GUI中将图像设置为框架的背景?

如何在Java的Swing GUI中将图像设置为框架的背景?

实现此目的的一种方法是重写paintComponent每次JPanel刷新时绘制背景图像的方法

例如,可以将子类化JPanel,并添加一个字段以保存背景图片,然后覆盖该paintComponent方法

public class JPanelWithBackground extends JPanel {

  private Image backgroundImage;

  // Some code to initialize the background image.
  // Here, we use the constructor to load the image. This
  // can vary depending on the use case of the panel.
  public JPanelWithBackground(String fileName) throws IOException {
    backgroundImage = ImageIO.read(new File(fileName));
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Draw the background image.
    g.drawImage(backgroundImage, 0, 0, this);
  }
}

(以上代码尚未经过测试。)

以下代码可用于将添加JPanelWithBackground到中JFrame

JFrame f = new JFrame();
f.getContentPane().add(new JPanelWithBackground("sample.jpeg"));

在此示例中,该ImageIO.read(File)方法用于读取外部JPEG文件

java 2022/1/1 18:19:04 有506人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶