在 JFrame 中更改 JPanel 背景颜色



>我正在尝试更改 JFrame 内部 JPanel 的背景。JFrame由JPanell组成,很像一个网格。我正在尝试更改 JFrame 内部的随机 JPanel,并查看每次通过循环时的颜色变化。这是我到目前为止得到的。

private static JPanel panel;
private static int index;
public static void main(String[] args)
{
    JFrame window = new JFrame();
    window. setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
    window.setSize(600, 600);
    GridLayout layout = new GridLayout(50, 50, 3, 3);
    panel = new JPanel(layout);
    panel.setSize(600, 600);
    //Initialize the JFrame with JPanels that
    //are all white.
    InitializeGrid(panel);
    window.add(panel);
    window.validate();
    window.setVisible(true);

    MainLoop();
}
private static void MainLoop()
{
      Component[] componentArrayTwo = panel.getComponents();
      int index = 0;
      while(true)
      {
        JPanel currentPanel = (JPanel) componentArrayTwo[index];
            currentPanel.setBackground(Color.GREEN);
            index++;
          if(index == 1600)
          {
              //Restart again
              index = 0;
          }
          //Colors everything back to white.
          Reset();
      }    
}
private static void InitializeGrid(JPanel panel)
{
      //40 x 40 = 1600
    for(int i = 0; i < 1600; i++)
    {
        JPanel cellPanel = new JPanel();
        cellPanel.setMinimumSize(new Dimension(3, 3));
        cellPanel.setMaximumSize(new Dimension(3, 3));
        cellPanel.setPreferredSize(new Dimension(3, 3));
        cellPanel.setBackground(Color.WHITE);
        panel.add(cellPanel);
    }
}
/*************************************************************************/
//NAME: Reset
//DESCRIPTION: Resets all the cells back to white which is executed on
//each iteration through the loop.
/*************************************************************************/
private static void Reset()
{
    Component[] componentArrayTwo = panel.getComponents();
    for(Component individualComponent : componentArrayTwo ) 
    {
        JPanel panelToColor = (JPanel) individualComponent;

        panelToColor.setBackground(Color.WHITE);
    }
}

如果我取消注释 panel.add(individualPanel) 行,这将显示颜色变化,但它会不断向 JFrame 添加越来越多的 JPaels。但是,注释此行可以让我更改颜色,但不会在 JFrame 中显示任何更改。我尝试更改此代码中的各种部分,但到目前为止我没有成功。应该发生的是,在每次通过循环时,我应该看到一个绿色的JPanel出现在JFrame的随机位置。如果有人能帮忙,我将不胜感激。

如果要使用 swing 制作动画,请使用javax.swing.Timer。了解如何使用摆动计时器

在此处和此处

以及此处和此处查看更多示例。

测试一下这个。它只改变一个面板的背景,而不是像您尝试的那样尝试使用多个面板。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class ColorChange extends JPanel {
    private static final int D_W = 300;
    private static final int D_H = 300;
    private final List<Color> colors;
    private final Random random;
    private Color bgColor = Color.BLUE;
    public ColorChange() {
        colors = createColorList();
        random = new Random();
        Timer timer = new Timer(500, new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                int index = random.nextInt(colors.size());
                bgColor = colors.get(index);
                repaint();
            }
        });
        timer.start();
    }
    private List<Color> createColorList() {
        List<Color> list = new ArrayList<>();
        list.add(Color.BLUE);
        list.add(Color.CYAN);
        list.add(Color.PINK);
        list.add(Color.ORANGE);
        list.add(Color.MAGENTA);
        list.add(Color.GREEN);
        list.add(Color.YELLOW);
        list.add(Color.RED);
        list.add(Color.GRAY);
        return list;
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(bgColor);
        g.fillRect(0, 0, getWidth(), getHeight());
    }
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(D_W, D_H);
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new ColorChange());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

最新更新