1 Attachment(s)
Problem with image in swing gui
I'm making a dice program that will displace a random image of a dice between 1 and 6, my problem is displaying and image in my program.
Here's my GUI source code:
Code Java:
package terninggui;
import java.awt.*;
import javax.swing.*;
public class GUI extends JPanel
{
Image ener = Toolkit.getDefaultToolkit().getImage("ener.png");
Terning minTerning = new Terning();
public void paintComponent(Graphics g){
g.drawImage(ener, 10,10,this);
}
}
And here's my main method source code:
Code Java:
package terninggui;
import javax.swing.*;
public class TerningGUI {
public static void main(String[] args) {
JFrame Vindue = new JFrame("Terning");
Vindue.add( new GUI());
Vindue.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Vindue.setSize(200,200);
Vindue.setVisible(true);
}
}
I've got my image in my source folder as seen in this screen shot
http://i.imgur.com/Xi3unl.png?1
Also worth noting in this screen shot is that the image name is in orange instead of blue, as if it's just a text, I don't how much it matters, but it's one of the things worth noting.
Thanks for reading my post, and I hope you can help, and I apologize for the danish in the source code, this is just ment to be a "training" project for me
Re: Problem with image in swing gui
Can you explain what your problem is?
The paintComponent method can be called many times. You should read the image file outside of the paintComponent method so it is only read one time.
Re: Problem with image in swing gui
My problem is that the image doesn't show, when I run the program, all I get is an empty window.
edit:
I moved it so I read my image outside the paintComponent, but it still doesn't show.
Re: Problem with image in swing gui
The code does not compile because the Terning class is missing.
When I remove that line and put in my image file, the code compiles and shows the image.
Make sure the image is in the folder where the program is looking for it to be.
Re: Problem with image in swing gui
Thanks a lot Norm that cleared up my issue :-D