Reputation: 33
I have reduced my codes to such a simple function: to show a picture on a window. But why does the picture not show up however I tried? I create a JFrame, and then created a JPanel which is expected to show the picture. Then add the panel to the frame. By the way, I imported the picture and double clicked it to get the url.
import java.awt.*;
import javax.swing.*;
import com.sun.prism.Graphics;
public class GUI {
JFrame frame=new JFrame("My game");
JPanel gamePanel=new JPanel();
public static void main(String[] args){
GUI gui=new GUI();
gui.go();
}
public void go(){
frame.setSize(300, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Background backPic=new Background();
backPic.setVisible(true);
frame.getContentPane().add(backPic);
JPanel contentPane=(JPanel) frame.getContentPane();
contentPane.setOpaque(false);
frame.setVisible(true);
}
class Background extends JPanel{
public void paintComponent(Graphics g){
ImageIcon backgroundIcon=new ImageIcon("file:///E:/eclipse/EL/backgroundPicture.jpg");
Image backgroundPic=backgroundIcon.getImage();
Graphics2D g2D=(Graphics2D) g;
g2D.drawImage(backgroundPic,0,0,this);
}
}
}
Upvotes: 1
Views: 52
Reputation: 2271
It's because you've imported com.sun.prism.Graphics
. It should be java.awt.Graphics
.
I would also get rid of the "file:///" bit from your path. And you also probably don't want to be loading the image on each paint event. Here's a better version of the Background class;-
class Background extends JPanel {
Image backgroundPic;
public Background() {
ImageIcon backgroundIcon=new ImageIcon("E:/eclipse/EL/backgroundPicture.jpg");
backgroundPic=backgroundIcon.getImage();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D=(Graphics2D) g;
g2D.drawImage(backgroundPic,10,10,this);
}
}
Upvotes: 2