java - 使用 JFrame 创建颜色网格?

标签 java swing colors jframe

有没有办法在 JFrame 中创建颜色网格 (8x12)?一直在研究一个项目,但到目前为止还没有找到太多帮助。如果有人可以向我提供任何文档链接,那就太好了!

最佳答案

我不太确定您要什么,但如果您要求在 JFrame 中显示 8x12 颜色网格,那么我可以提供答案。

您想要使用paint方法,并在该方法中放置两个for循环。这是一个例子:

import javax.swing.*;
import java.awt.*;
public class myJFrame extends JFrame{
    public void paint(Graphics g) {//This method is what paints the JFrame, as its name implies.
        super.paint(g);
        int sizeX = this.getWidth()/8;//Takes the size of current JFrame
        int sizeY=this.getWidth()/12;
        for(int x=0;x<sizeX;x++)//These for loops go through an 8x12 grid of the JFrame
            for(int y=0;y<sizeY;y++) {
                g.setColor(new Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256)));//This just creates a random color, you can replace this with anything else
                g.fillRect(x*sizeX,y*sizeY,sizeX,sizeY);//Creates the grid
            }
    }
    public static void main(String[] args) {
        JFrame f=new myJFrame();//If you already have a JFrame implemented, you'll have to replace its declaration with this line of code
        //f.setUndecorated(true);//If you want evenly distributed grids, uncomment this line.
        f.setVisible(true);//Sets the JFrame to be visible
        f.setSize(80,120);//This size is arbitrary, you can replace it with anything, and the program will still work
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //If you want the grid to be perfectly distributed, then uncomment the line below.

    }
}

关于java - 使用 JFrame 创建颜色网格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55270553/

相关文章:

java - JComboBox 自动完成

java - JList(与数组列表链接)添加元素导致内存不足或消失

javascript - 将 0-1 值转换为十六进制颜色?

java - 如何用java android jdk播放外部视频?

java - Java中的编码问题

java - Jetty - 如何使 Camel 应用程序将事件记录到 hawtio 日志选项卡

ubuntu - Debian Ubuntu : most pager does not print the required foreground colors

java - 在 Windows 10 上升级到 Java 11

java - 更新图形

android - 使 Android Lollipop 中状态栏的工具栏颜色变暗