Can someone explain why in the image icon function my photo of a chess piece wont show up on the board when i run the the program. I added the function to the main but it wont seem to show up the image icon starts between lines 36-39.
package chess;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Toolkit;
public class chess extends JPanel
{
final static int WINDOW_WIDTH=600; // Width of window
final static int WINDOW_HEIGHT=600; // Height of window
public void paint(Graphics g)
{
// Create Chess board
g.fillRect(100, 100, 400, 400); // White squares
for(int i = 100; i <= 400; i+=100){
for(int j = 100; j <= 400; j+=100){
g.clearRect(i, j, 50, 50); // Black squares
}
}
for(int i = 150; i <= 450; i+=100){
for(int j = 150; j <= 450; j+=100){
g.clearRect(i, j, 50, 50);
//Print out image on board
ImageIcon image;
image=new ImageIcon("brook.gif");
g.drawImage(image.getImage(),0*66,7*44,null);
}
}
}
public static void main(String[] args)
{
JFrame window = new JFrame("Chess"); // Create Frame and give it the method named "window"
window.setSize(WINDOW_WIDTH,WINDOW_HEIGHT); // sets the size of the window
window.getContentPane().add(new chess()); // adds the chess board to the window
window.setLocationRelativeTo(null); // Sets the window in the middle of the screen by setting it null
window.setBackground(Color.BLUE); // Window background color set to gray
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // When the close option is clicked the program will stop running
window.setVisible(true); // Makes the window visible
}
}
Firstly your Project Hierarchy should look something like this
Then you need to change
image=new ImageIcon("brook.gif");
to following
image=new ImageIcon(getClass().getResource("/brook.gif"));
As a final not Make sure you are typing the name of your gif
as it is.
Always remember it is case sensitive
For the above Hierarchy, I have to write this
image=new ImageIcon(getClass().getResource("/sphere.png"));
Not
image=new ImageIcon(getClass().getResource("/Sphere.png")); // or
image=new ImageIcon(getClass().getResource("/SPHERE.png"));
//The above 2 lines won't work.