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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…