Reputation: 5
I have googled this and searched through this site to try and get an Image to show up using Swing, but every time i implement the code i find online it doesn't work. I have no idea what i am doing wrong, can anyone help me?
package Game;
import java.awt.Dimension;
import java.awt.Graphics;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Amazing {
private int width = 300;
private int height = width / 16 * 9;
private int scale = 3;
private static Graphics g;
private static JFrame frame = new JFrame();
private static JPanel panel = new JPanel();
public Amazing(){
Dimension size = new Dimension(width*scale, height*scale);
frame.setPreferredSize(size);
frame.setResizable(false);
frame.setTitle("Amazing!");
frame.add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args){
Amazing amazing = new Amazing();
Character character = new Character();
character.paintComponent(g);
}
}
package Game;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class Character extends JPanel{
private BufferedImage image;
public Character(){
try {
image = ImageIO.read(new File("E:\\Libraries\\Documents\\Java Stuff\\workspace\\Java_Final\\narwhal.png"));
} catch (IOException ex) {
// handle exception...
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 50, 50, null); // see javadoc for more info on the parameters
}
}
Upvotes: 0
Views: 86
Reputation: 324207
Amazing amazing = new Amazing();
All that line of code does is create a frame and then add an empty panel to it. Since the panel is empty there is nothing to paint.
Character character = new Character();
character.paintComponent(g);
You should never invoke the paintComponent() method directly. Swing will invoke that method when a component needs to be repainted. Anyway, creating a Character object does nothing. That object is just sitting in memory. It is not added to a GUI so it can never be painted.
I suggest you forget about custom painting and just use a JLabel to display an image. Read the section from the Swing tutorial on How to Use Labels for a working example. Not only that, the tutorial will show you how to better structure your code. You should not be using static variables. Start with the working example and then customize it to use your image.
Upvotes: 1