首页 > 解决方案 > 有没有办法在 JPanel 的扩展类中调用 setBackgroud()

问题描述

我正在模拟康威的人生游戏。我想创建一组扩展“JPanel”的“Mybox”类型的盒子。在每个框内,我想在程序启动时调用函数 SetBackground()。这是我最接近让它工作的地方

package conwaysGameOfLife;

import java.awt.Color;
import java.awt.Panel;

import javax.swing.JPanel;

public class MyBox extends JPanel{
    public void setBackground(Color color){
        super.setBackground(color);
    }
    public static void main(String[] args) {
        setBackground(Color.white);
    }
}

当我输入这个时,我收到错误,告诉我将 setBackground() 设为静态,但是当我这样做时,我在 supper 关键字下得到一个错误。

标签: javajframejpanel

解决方案


setBackground() 不应该是静态的。在您的 main() 中,您需要创建一个 MyBox 实例并使用该实例:

MyBox box = new MyBox();
box.setBackground( Color.red );

例如:

public class MyBox extends JPanel{

    public MyBox() {
         this( Color.GREEN );
    }

    public MyBox(Color color){
        setBackground(color);
    }

    public static void main(String[] args) {
        // Create an instance with green background
        // using the default constructor:
        MyBox greenBox = new MyBox();

        // or use the other constructor 
        MyBox redBox = new MyBox(Color.RED);
        // then later you can change the color:
        redBox.setBackground(Color.white);
    }
}

推荐阅读