java gridlayout gui - too many panels?
I am trying to create a board game in Java however i am pretty new to GUI's. The problem is that the coloured panels are being added to the grid layout and so are the images so they end up being packed side by side.
I would like the images to be on top of the other color panels so it looks like a board with pieces (the images), on top.
the following code should create four colored squares with four of the same images on top, instead they just end up side by side.
import java.awt.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class test extends JFrame {
private static JPanel gridLayout = new JPanel(new GridLayout(2, 2));
private static ImageIcon img = new
ImageIcon(System.getProperty("user.dir") + "/images/an_image.png");
private sta开发者_如何转开发tic String[] boardTest = {
"i", "i",
"i", "i" };
public test() {
BorderLayout layout = new BorderLayout();
setLayout(layout);
add(gridLayout);
}
private static JLabel getPieceObject(String strPieceName) {
JLabel images;
if (strPieceName.equals("i")) {
images = new JLabel(img);
} else {
images = new JLabel();
}
return images;
}
private static void displayBoard() {
for (int i = 0; i < 4; i++) {
gridLayout.add(getPieceObject(boardTest[i]), BorderLayout.CENTER);
// this creates the color squares of the board//
JPanel panel = new JPanel(); //error
if (i % 2 == i/2 % 2) {
panel.setBackground(Color.RED);
} else {
panel.setBackground(Color.BLUE);
}
gridLayout.add(panel);
////////////////////////////////////////////////
gridLayout.validate();
}
}
public static void main(String[] args) {
displayBoard();
test app = new test();
app.setSize(200, 200);
app.setVisible(true);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
You could set the image as the background of the panel, like so.
精彩评论