【问题标题】:How a JPanel displays different colors from an array of colors?JPanel 如何从一组颜色中显示不同的颜色?
【发布时间】:2012-08-24 02:20:29
【问题描述】:

问题是当我将正方形 JPanel 的背景颜色设置为 square.setBackground(colors[j]) 时,正方形仅绘制颜色列表中的第一种颜色而不显示其他 3 种颜色。这是我的代码:

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

@SuppressWarnings({ "unused", "serial" })

public class RegionPartition extends JFrame
{
    JLayeredPane layeredPane;
    JPanel regionBoard;
    JLabel regionPiece;

    private static int DELAY = 200;

    private Color[] colors = new Color[]{Color.PINK, Color.GREEN, Color.BLACK, Color.RED};

    public RegionPartition()
    {
        Dimension boardSize = new Dimension(500, 500);

        //  Use a Layered Pane for this this application
        layeredPane = new JLayeredPane();
        getContentPane().add(layeredPane);
        layeredPane.setPreferredSize(boardSize);

        regionBoard = new JPanel();

        layeredPane.add(regionBoard, JLayeredPane.DEFAULT_LAYER);

        regionBoard.setLayout( new GridLayout(4, 4) );

        regionBoard.setPreferredSize( boardSize );
        regionBoard.setBounds(0, 0, boardSize.width, boardSize.height);

        Random random = new Random();


        for (int i = 0; i < 16; i++) {          
            JPanel square = new JPanel(new BorderLayout());
            square.setBorder(BorderFactory.createLineBorder(Color.black));
            regionBoard.add( square );  

            square.setBackground(Color.green);

            int j=0;

            square.setBackground(colors[j]);

            j++;
        }
    }

    {
        JPanel panel = new JPanel()  
        {  
            Clients[] c = new Clients[128];

            Random random = new Random();

            private final int SIZE = 450;
            private int DELAY = 9999999;
            public void paintComponent (Graphics g)
            {
                super.paintComponent(g);

                for (int i=0; i<c.length; i++)
                {
                    int x = ( int ) ( random.nextFloat() * SIZE ) + 10;
                    int y = ( int ) ( random.nextFloat() * SIZE ) + 10;

                    g.drawOval( x, y, 10, 10 );
                    g.fillOval(x, y, 10, 10);
                }

                for (int j=0; j<DELAY; j++)
                {
                    repaint();
                }
            }
        };  

        panel.setOpaque(false);  

        //Set the glass pane in the JFrame  
        setGlassPane(panel);  

        //Display the panel  

        panel.setVisible(true);  
    }

    public static void main(String[] args)
    {
        JFrame frame = new RegionPartition();

        frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE );
        frame.pack();
        frame.setResizable(true);
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);

    }

    protected void paintComponent(Graphics g)
    {
        // TODO Auto-generated method stub
    }
}

【问题讨论】:

  • 每行之间的额外间距不利于可读性,缩进可以! j 在设置颜色之前总是设置为 0...
  • 顺便说一句:你不应该在 paintComponent() 方法中调用 repaint() (这将导致你的组件被一遍又一遍地绘制)。此外,多次调用 repaint() (你用循环调用它 200 次)是没有用的,因为它们被合并为一个调用。

标签: java arrays swing colors jpanel


【解决方案1】:

那是因为你总是在每次迭代时将 j 设置为 0:

    int j=0;

    square.setBackground(colors[j]);

    j++;

您可能想要将 j 更改为 i 或执行嵌套循环,这取决于您在这里真正想要做什么。

如果您想让所有 16 个方格都以网格状方式具有所有四种颜色,您可能需要将循环更改为:

     for (int i = 0; i < 16; i++) {          
        JPanel square = new JPanel(new GridLayout(2,2));
        square.setBorder(BorderFactory.createLineBorder(Color.black));
        regionBoard.add( square );  



        for(int j=0; j<4; ++j){
          JPanel insideSquare = new JPanel();
          insideSquare.setBackground(colors[j]);
          square.add(insideSquare);
        }
    }

【讨论】:

  • 我想改变 JPanel 方块的背景颜色。问题是,即使我使用 for 循环,它也只绘制数组 Color 的一种颜色,特别是在这种情况下,它只绘制数组的最后一种颜色!改成i是什么意思??
  • @user1633202 "它只绘制数组 Color 的一种颜色,特别是在这种情况下它只绘制最后一种颜色" 那是因为 JPanels 只能有一种背景颜色,你是每次都覆盖它。
  • 还应该使用取模('%')运算符,因为数组中只有4种颜色,但循环重复了16次
  • 通过更改 colors[j] 为 colors[i] 将把每个面板绘制为数组的一种颜色作为 1:1 映射,如果你有 16 种颜色
  • 如果目标是简单地绘制 2x2 网格,则没有理由使用多个 JPanel。在一个面板中简单地覆盖paintComponent,然后将其大小划分为四个相等的正方形来着色会更加干净和传统。
【解决方案2】:

因为您的 color 数组中只有 4 种颜色,但您的循环索引超过了这个,您可以使用:

square.setBackground(colors[ i % colors.length]);

改变方块的颜色。

【讨论】:

    【解决方案3】:

    您正在 for 循环范围内实例化 int j,因此它的值不会在多次迭代中保留。您应该在代码中的某个位置声明它,以使其作用于整个 for 循环。

    int j = 0;
    <for loop>
        square.setBackground(colors[j]);
        j++;
    <end for>
    

    但是,在这种情况下,您的 j 服务于 i 的目的,其中 i 足以作为数组索引。完全删除j 并改为执行以下操作会更正确:

        square.setBackground(colors[i]);
    

    【讨论】:

    • 我按照你的建议做了,但是我有编译错误:线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 4 在 RegionPartition.(RegionPartition.java:55) 在 RegionPartition。主(RegionPartition.java:109)
    • 这是运行时错误,不是语法错误。无论如何,如果你正确地实现了int j,就会发生这种情况,所以我必须知道你的颜色目标是什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 2016-02-24
    • 2020-09-26
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    相关资源
    最近更新 更多