Reputation: 155
I have an image that has to make up a 8x8 grid, so it is a background for the board.
I have been told it is possible to do this using ImageIcon and a JLabel, which I tried and it doesn't seem to work.
Here is the code:
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
square=new JLabel();
square.setIcon(icon);
chessBoard.add( square );
}
}
The full code: http://pastebin.com/YdavUmGz
Am I doing something horribly wrong with this background image?
Any help would be appreciated, thanks in advance.
Upvotes: 1
Views: 195
Reputation: 23025
Are you looking for something like this?
import java.awt.*;
import javax.swing.*;
public class ChessBoard extends JFrame {
private JPanel panel;
public ChessBoard() {
panel = new JPanel();
panel.setLayout(new GridLayout(8, 8, 0, 0)); //Create the board
//Add JLabels
for (int i = 0; i < 64; i++) {
JLabel label = new JLabel();
label.setIcon(
new ImageIcon(getClass().getResource("images/face.png")));
panel.add(label);
}
//Add the panel to the JFrame
this.add(panel);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ChessBoard();
}
});
}
}
Upvotes: 3