Reputation: 155
I'm trying to create an 8x8 grid composed of pre made images to be used for a board game, however I am having difficulty loading the images.
Dimension Size = new Dimension(400, 400);
layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(Size);
getContentPane().add(layeredPane);
board.setLayout(new GridLayout(8,8));
board.setPreferredSize(Size);
board.setBounds(0, 0, Size.width, Size.height);
layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);
// Load squares to board
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
JPanel square = new JPanel( new BorderLayout() );
square. // Load .jpg here?????
board.add( square );
}
}
The only method I know is ImageIcon, but that doesn't seem to work... So I'm stuck.
Any help would be appreciated, Thanks.
Upvotes: 1
Views: 426
Reputation: 7076
Try this code snippet, adapted from java2s.com:
class ImagePanel extends JPanel {
private Image img;
public ImagePanel(URL imgURL) {
this(new ImageIcon(imgURL).getImage());
}
public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(this), img.getHeight(this));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null);
}
@Override
public void paintComponent(Graphics g) {
super.paint(g);
g.drawImage(img, 0, 0, this);
}
}
You can add those ImagePanels inside the JPanel
Upvotes: 0
Reputation: 324128
ImageIcon should work fine. See the Swing tutorial on How to Use Icons for more information and examples.
Upvotes: 3