java gridlayout gui - 太多面板?

时间:2010-11-05 08:20:52

标签: java swing

我正在尝试用Java创建一个棋盘游戏但是我对GUI很新。问题是彩色面板被添加到网格布局中,图像也是如此,因此它们最终被并排打包。

我希望这些图像位于其他颜色面板的顶部,因此它看起来像一块带有碎片(图像)的板,位于顶部。

以下代码应创建四个彩色方块,顶部有四个相同的图像,而不是它们并排放置。

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 static 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);
}

}

1 个答案:

答案 0 :(得分:1)

您可以将图片设置为面板的背景like so

相关问题