java - 如何在网格框中随机填充颜色

标签 java grid image

如何在网格框中随机填充颜色?

而不是如图所示有序:

Grid http://www.freeimagehosting.net/uploads/4ed76557de.jpg

public class grid extends JPanel{
    Label one = new Label();
    Label two = new Label();
    Label three = new Label();
    Label four = new Label();

    public static void main(String[] args){
        JFrame jf=new JFrame();
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.add(new YAnswers());
        jf.pack();
        jf.setVisible(true);
    }

    grid (){
       int rows=10; int cols=10;
       setLayout(new GridLayout(rows,cols));
       add(one); one.setBackground(Color.red);
       add(two); two.setBackground(Color.orange);
       add(three); three.setBackground(Color.green);
       add(four); four.setBackground(Color.black);
       boxes[] bx=new boxes[rows*cols];

        for(int i=0;i<rows*cols;i++){
            System.out.println("i"+i);
            bx[i]=new boxes();
            if(i%2<1)
                bx[i].setColor(1);
            add(bx[i]);
        }
    } //end grid()
}

最佳答案

您可以使用Math.random获得随机颜色:

new Color( (float)Math.random(), (float)Math.random(), (float)Math.random() );

顺便说一句:Java 中的类名以大写字母开头,因此请使用 Grid 而不是 grid


编辑

以下代码使用 GridBagLayout产生这个结果:

alt text http://img214.imageshack.us/img214/5426/so2374295.png

public Grid ()
{
    final Color BACKGROUND = Color.LIGHT_GRAY;
    final Color[] colors = new Color[]
        {Color.BLACK, Color.BLACK, Color.BLUE, Color.BLUE};

    final int ROWS=10;
    final int COLS=10;

    setBackground(Color.BLACK);
    setLayout(new GridBagLayout());

    Label[][] label = new Label[ROWS][COLS];

    GridBagConstraints gc = new GridBagConstraints();
    gc.weightx = 1d;
    gc.weighty = 1d;
    gc.insets = new Insets(0, 0, 1, 1);
    gc.fill = GridBagConstraints.BOTH;

    // fill the whole panel with labels
    for( int r=0 ; r<ROWS ; r++) {
        for( int c=0 ; c<COLS ; c++) {
            Label l = new Label();
            l.setBackground(BACKGROUND);
            gc.gridx = r;
            gc.gridy = c;
            add(l, gc);
            label[r][c] = l;
        }
    }

    // now find random fields for the colors defined in BACKGROUND
    for(Color col : colors) {
        int r, c;
        do { // make sure to find unique fields
            r = (int)Math.floor(Math.random() * ROWS);
            c = (int)Math.floor(Math.random() * COLS);
        } while(!label[r][c].getBackground().equals(BACKGROUND));
        label[r][c].setBackground(col);
    }
}

关于java - 如何在网格框中随机填充颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2374295/

相关文章:

java - 安卓服务 START_STICKY START_NOT_STICKY

Java eclipse 路径文件可执行文件

java - 将时间戳转换为时间会给出错误的时间

html - 将图片添加到网格中 - ExtJS

java - 在Java中,创建支持不同分辨率/显示模式的应用程序

python - 如何根据内容将一组图像文件聚类到不同的文件夹

java - java服务器和javascript之间的通信

网格排列中的CSS滑出div

html - 独特的 Figcaption 更改网格布局中的图像大小

c# - 如何将位图图像保存为 JPEG