当前位置: 首页 > 知识库问答 >
问题:

更改JFrame中的JPanel背景色

白昊乾
2023-03-14

我试图在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添加越来越多的JPanels。但是,注释这一行可以让我更改颜色,但不会显示JFrame中的任何更改。我试着修改了这段代码中的不同部分,但到目前为止都没有成功。应该发生的是,在循环的每一次传递中,我都应该看到一个绿色的JPanel出现在JFrame中的随机点上。如果有人能帮忙,我将不胜感激。

共有1个答案

陈飞
2023-03-14

如果希望使用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);
            }
        });
    }
}
 类似资料:
  • 我无法让JPanel改变颜色。我也不能让JFrame改变颜色。我在网上查过...我还有一个程序,它有几乎相同的代码来设置JPanel和JFrame。我就是不能让它起作用。 下面是我的主要方法: 编辑:稍后在我的主要方法中有 下面是JPanel的构造函数: 背景颜色保持默认灰色。

  • 我需要帮助的java swing为GUI。我已经包含了“frame.getContentPane().setbackground(color.cyan);”到代码,但框架的背景颜色不变?谢谢你。

  • 我在Driver类中使用setBackground()方法来更改背景颜色,但它不起作用。 请为我提供解决方案,我如何更改JFrame的背景色?我只想让JFrame的背景色从默认颜色变成白色。

  • 有没有办法清除JFrame的背景色或至少将其更改回默认颜色? 更新:谢谢你的回答,但是看起来我好像意外地得到了我想要的答案。我刚拍了一帧。getContentPane()。setBackground(null)将其恢复为默认背景。我在看了评论后想了想,所以如果没有你的帮助,我不可能做到这一点。再次感谢。

  • 我有一个java作业,其中我需要更改GUI的背景颜色,这取决于用户选择的列出不同颜色的单选按钮。我的程序有一个JFrame来保存所有东西,然后在这个框架中有3个JPanels(1个指令区,1个单选按钮网格,1个结果文本字段)。 My action listener当前正在使用以下语句设置背景颜色:getContentPane().SetBackground(color.Decode(ColorMa

  • 我有一个带有卡布局组件的JFrame。我正在使用卡布局在应用程序执行的不同时刻在不同的JPanel之间切换。在某些时候,我正在使用摇摆工人对象来生成一些XML文件。在这段时间里,我想在我的窗口中显示另一个JPanel,告诉用户等待。在这个JPanel上,我想在3个标签之间切换。 吉列布尔1会说:“请稍候。 吉拉贝尔2会说:“请稍候..” 吉拉贝尔3会是:“请稍候...” 现在代码如下: Swing