java - 有没有办法在 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 关键字下得到一个错误。
解决方案
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);
}
}
推荐阅读
- cookies - 为同级域隔离同站点 cookie
- java - 我已经覆盖了paintComponent(),为什么我的形状没有出现?
- java - 在向不同来源调用 GET 和 POST 请求时收到 400 个错误请求
- string - 使用 SwiftUI 在 UserDefaults 中保存 TextField 中的字符串
- angular - 如何使用二维角度虚拟滚动?
- ios - 将字典作为单个数组存储到 userdefault - Alamofire - SwiftyJSon
- rust - 锈打印!问题 - println 宏内部的奇怪行为
- mysql - XAMPP:MySQL 意外关闭,已尝试重新安装一切仍然无法正常工作
- javascript - 消除重复无法按预期工作
- javascript - 如何在 javascript 中生成的动态 html 元素上应用 .css 规则