繁体   English   中英

在JFrame中更改JPanel背景颜色

[英]Change JPanel Background Color in JFrame

我正在尝试在JFrame中更改JPanel的背景。 JFrame由JPanels组成,非常类似于网格。 我正在尝试在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中添加越来越多的JPanel。 但是,注释此行使我可以更改颜色,但在JFrame中不显示任何更改。 我尝试更改此代码中的各个部分,但到目前为止,我一直没有成功。 应该发生的是,在每次循环中,我都应该看到一个绿色的JPanel出现在JFrame中的随机点上。 如果有人可以帮忙,我将不胜感激。

如果要使用swing设置动画,请使用javax.swing.Timer 请参阅如何使用Swing计时器

在此处此处此处此处查看更多示例。

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

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);
            }
        });
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM