设置JFrame背景,为什么这不起作用?

时间:2014-07-17 13:39:04

标签: java swing

我想为我的jFrame设置背景,我正在使用此代码:

import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class DemoBackgroundSwing extends JPanel {

  private Image img;

  public DemoBackgroundSwing() {
      System.out.println("done");
    img = Toolkit.getDefaultToolkit().createImage("red.png");
    System.out.println("done");
    loadImage(img);
    System.out.println("done");
  }

  private void loadImage(Image img) {
    try {
      MediaTracker track = new MediaTracker(this);
      track.addImage(img, 0);
      track.waitForID(0);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  protected void paintComponent(Graphics g) {
    setOpaque(false);
    System.out.println("done");
    g.drawImage(img, 0, 0, null);
    super.paintComponent(g);
  }

  public static void main(String... argv) {
    JFrame frame = new JFrame("Demo Background Image");
    DemoBackgroundSwing back = new DemoBackgroundSwing();
    System.out.println("done");
    frame.getContentPane().add(back);
    frame.setSize(400, 287);
    frame.setVisible(true);
  }
}

当我执行它时,在系统输出中我有5个“完成”。所以这意味着所有任务都被执行了。 我不明白错误在哪里。请帮帮我!

1 个答案:

答案 0 :(得分:3)

打印已加载图像的宽度(如果为-1),则图像未正确加载。

img = Toolkit.getDefaultToolkit().createImage("red.png");
System.out.println(img.getWidth(null)); // check what it prints

值得在Loading Images Using getResource

上阅读 Java Tutorial

您可以根据图片位置尝试任何一种。

// Read from same package 
ImageIO.read(getClass().getResourceAsStream("c.png"));

// Read from images folder parallel to src in your project
ImageIO.read(new File("images/c.jpg"));

// Read from src/images folder
ImageIO.read(getClass().getResource("/images/c.png"))

// Read from src/images folder
ImageIO.read(getClass().getResourceAsStream("/images/c.png"))

Read more...


有些要点: