java - Can't set color to JPanel in Java
问题描述
I have just started with Graphics in java, and I'm already stuck. I have tried to set the color of the JPanel to red but nothing seems to work! Any help is highly appreciated.
JFrame class:
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Color;
public class redBoxFrame{
public static void main(String[]args){
JFrame f = new JFrame();
f.setSize(400, 200);
f.setTitle("A red box");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new redBoxPanel();
p.setBackground(Color.RED);
f.add(p);
f.setVisible(true);
}
}
JPanel class:
import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.Color;
public class redBoxPanel extends JPanel {
public void paintComponent(Graphics g){
g.fillRect(0, 0, 100, 100);
g.setColor(Color.RED);
}
}
As you can see I have both tried to declare the color in the JFrame class and in the JPanel class but none of them seem to work. Thank you!
解决方案
I think you you are missing super.paintComponent(g);
in your painComponent method.
推荐阅读
- flutter - 颤振:未来
返回 null 但如果打印它有值 - java - api 文档 Swagger 中未添加的 ExclusiveMaximum 注释
- mongodb - MongoDB 指南针在“激活插件”屏幕上停止
- python - Get specific value BeautifulSoup (parsing)
- pine-script - Pine Script : 直方图的颜色不能着色
- python-3.x - 使用 python openpyxl 的多列样式
- git - 如何合并已发布的修补程序以开发与拉取请求中的冲突?
- c++ - 如何找出`duration_cast的真实类型
(steady_clock::now().time_since_epoch()).count()` - scala - 如何用 Slick 中的另一个子查询值更新列?
- javascript - 为什么数字以零开头时会发生变化?