Reputation: 1
I'm trying to right a function that creates a JFrame that contains an image. Problem is I only get an empty JFrame (no errors). Is there a better way to do this? Here is the class that contains the function:
public class Play extends JFrame
{
protected static ImageIcon icon = new ImageIcon("C:\\Users\\Fadil\\Desktop\\Coding\\civii\\earth.jpg");
protected static JLabel label = new JLabel(icon);
protected static JFrame f = new JFrame("Age Of")
public static void PlayStart()
{
f.getContentPane().add(label);
f.repaint();
f.setVisible(true);
}
}
Upvotes: 0
Views: 37
Reputation: 1009
simply do the following 1- create Panel class and use media tool kit to get image in your class path lie this class P extends JPanel { Image bg = null;
P() {
MediaTracker mt = new MediaTracker(this);
bg = Toolkit.getDefaultToolkit().getImage("yourimage");
mt.addImage(bg, 0);
try {
mt.waitForAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int imwidth = bgimage.getWidth(null);
int imheight = bgimage.getHeight(null);
g.drawImage(bg, 1, 1, null);
}
}
2- add the panel to your frame to the frame
public class JF extendts JFrame{
public JF(){
add(new P()) ;
sitSize(300,200) ;
}
}
Upvotes: 2