Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

java - setting a JFrame background, why this doesn't work?

I want to set a background to my jFrame, and I'm using this code:

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);
  }
}

when I execute it, in system out I have 5 "done". so this means that all tasks are executed. I don't understand where's the error. Please Help me!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Print the width of loaded image if it's -1 then image is not properly loaded.

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

It's worth reading Java Tutorial on Loading Images Using getResource


You can try any one based on image location.

// 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...


Some Points:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...