Reputation: 33
My current code, interestingly works with another IDE(JGrasp), although I am currently trying to create a game which uses networking. Eclipse allows networking on a single computer. For some reason, this method Im posted, which adds imagines to an array of JLabel, does not work with eclipse? I am new with eclipse and not sure why this is happening?
private JPanel createBoard()
{
// Instantiate Panel with a GridLayout
board = new JPanel();
board.setLayout(new GridLayout(10,10));
// Fill the Panel with an Array of Labels
// Checks for exception
boardSpotArray = new JLabel[100];
try
{
for (int x = 0; x < boardSpotArray.length; x++)
{
boardSpotArray[x] = new JLabel();
boardSpotArray[x].setIcon(new ImageIcon(x + ".jpg"));
board.add(boardSpotArray[x]);
}
}
catch (IndexOutOfBoundsException exception)
{
System.out.println("Array drawer not available, " + exception.getMessage());
}
// return panel
return board;
}
Upvotes: 1
Views: 1694
Reputation: 36
Complete code in Eclipse for you
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class oo {
public static JPanel createBoard()
{
// Instantiate Panel with a GridLayout
JPanel board = new JPanel();
board.setLayout(new GridLayout(10,10));
// Fill the Panel with an Array of Labels
// Checks for exception
JLabel[] boardSpotArray = new JLabel[100];
try
{
for (int x = 0; x < boardSpotArray.length; x++)
{
boardSpotArray[x] = new JLabel();
boardSpotArray[x].setIcon(new ImageIcon("healthy-heart.jpg"));
board.add(boardSpotArray[x]);
}
}
catch (IndexOutOfBoundsException exception)
{
System.out.println("Array drawer not available, " + exception.getMessage());
}
// return panel
return board;
}
public static void main(String[] args){
JFrame frame=new JFrame();
JPanel panel=createBoard();
frame.getContentPane().add(panel);
frame.setSize(100, 100);
frame.pack();
frame.setVisible(true);
}
}
"healthy-heart.jpg"
can be replaced with any other image.
Upvotes: 0
Reputation: 209012
If for example boardSpotArray[0]
is "firstImage"
, then your relative file path will be "firstImage.jpg"
. In such a case with Eclipse, and without using any special loaders or resource getters, the IDE will first look for the image in the project root. So your file structure should look like this
ProjectRoot
firstImage.jpg <-- image as direct child of project root
src
bin
Edit:
If your images are in the src
folder
ProjectRoot
src
0.jpg <-- image in src
1.jpg
2.jpg
Then your path should look like this
new ImageIcon("src/" + x + ".jpg")
Upvotes: 1