簡體   English   中英

jframe中的網格布局面板

[英]grid layout panels in a jframe

我將如何使用gridlayout和面板創建類似於棋盤格圖案的框架? 似乎我無法在一個for循環中創建具有兩種不同顏色的兩個面板。

import javax.swing.*;
import java.awt.*;

@SuppressWarnings("serial")
public class test extends JFrame {
    public test() {

        this.setSize(400, 400);


        JPanel content = new JPanel(new GridLayout(4,4));
        for(int i = 0; i < 8; i++) {
            JPanel panel = new JPanel();
            panel.setBackground(Color.RED);
            content.add(panel);

            JPanel panel2 = new JPanel();
            panel.setBackground(Color.BLUE);
            content.add(panel2);
        }

    //  for(int i = 0; i < 8; i++) {
    //      JPanel panel = new JPanel();
    //      panel.setBackground(Color.BLUE);
    //      content.add(panel);
    //  }

        this.add(content);
    }

    public static void main(String[] args) {
        test app = new test();
        app.setVisible(true);
        app.setResizable(false);
        app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
@SuppressWarnings("serial")
static class Test extends JFrame {
  public Test() {           
    this.setSize(400, 400);
    int size = 8;

    JPanel content = new JPanel(new GridLayout(size,size));

    for (int i = 0; i < size*size; ++i) {
      JPanel panel = new JPanel();
      panel.setBackground( i % 2 == i/size % 2 ? Color.RED : Color.BLUE);
      content.add(panel);
    }
    this.add(content);
  }
}

您可以直接處理索引,必須在每個單元格的顏色之間切換,並為每行開始不同的顏色。

錯字(注意panel2中的2):

panel2.setBackground(Color.BLUE);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM