开发者

grid layout panels in a jframe

开发者 https://www.devze.com 2023-01-23 04:41 出处:网络
How would i be able to use gridlayout and panels to create a frame that resembles a checkered board pattern? it would seem that i can\'t create two panels with two diferent colors within the one for-l

How would i be able to use gridlayout and panels to create a frame that resembles a checkered board pattern? it would seem that i can't create two panels with two diferent colors within the one for-loop.

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);
            开发者_如何学Ccontent.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);
  }
}

You can work directly on indices, you have to switch between colors every cell and starting for a different color for every row.


Typo (note the 2 in panel2):

panel2.setBackground(Color.BLUE);
0

精彩评论

暂无评论...
验证码 换一张
取 消