有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用户界面如何在JavaGUI中为按钮创建各种颜色?

我用这段代码在JavaGUI中创建了一系列按钮,正好是20个按钮,有20种不同的颜色。然而,不知何故,我不能,如果我使用这段代码,我会把所有20个按钮都涂成一种相同的颜色。如何在每个按钮中使用不同的颜色为它们着色?先谢谢你。注意,在代码中,我没有使用列出的数组

        setTitle("My Frame");
        setSize(500, 200);
        setLayout(new GridLayout(0, 5));

        int R = (int) (Math.random()*256);
        int G = (int) (Math.random()*256);
        int B = (int) (Math.random()*256);
        Color color = new Color(R, G, B);

        for (int i = 0; i < 20; i++)
        {
            JButton button = new JButton(Integer.toString(i));
            setBackground(color);
            add(button);
        }
        setVisible(true);

共 (2) 个答案

  1. # 1 楼答案

    变量RGB和随后的color在循环for开始之前被分配一个随机值。然后,在整个循环中,它们保留相同的值,因此所有按钮的颜色都相同

    尝试在循环的每个迭代中创建一个新的Color值:

    for (int i = 0; i < 20; i++)
    {
        int R = (int) (Math.random()*256);
        int G = (int) (Math.random()*256);
        int B = (int) (Math.random()*256);
        Color color = new Color(R, G, B);
    
        JButton button = new JButton(Integer.toString(i));
        setBackground(color);
        add(button);
    }
    

    现在循环的每个迭代都会为RGB(和color)获得自己不同的随机值

  2. # 2 楼答案

            setTitle("My Frame");
            setSize(500, 200);
            setLayout(new GridLayout(0, 5));
    
            for (int i = 0; i < 20; i++)
            {
                int R = (int) (Math.random()*256);
                int G = (int) (Math.random()*256);
                int B = (int) (Math.random()*256);
                Color color = new Color(R, G, B);
                JButton button = new JButton(Integer.toString(i));
                setBackground(color);
                add(button);
            }
            setVisible(true);