这是关于JPanel
的java代码:
class Battle_field extends JPanel{
public List<Image_Obj> pics_to_be_drawn;
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(pics_to_be_drawn.get(0).Get_the_buf_img() , 41, 41, 59, 59, Color.black, null);
}
}
当我设置 GUI 时:
added_panel= new Battle_field();
added_panel.setBorder(new LineBorder(SystemColor.activeCaption, 3));
added_panel.setBounds(27, 10, 397, 630);
added_panel.setBackground(Color.white);
this.getContentPane().add(added_panel);
我发现上面创建Battle_field()
对象会自动调用paintComponent
。
But here, I didn't initialize the variable "pics_to_be_drawn" yet,so if it is called, it would cause compiler error. Is this design unavoidable?
As you do so, it's necessary to happen? I wanna know this very much and of course the solution.
附注:
根据官方文档,只有当我调用repaint()
时,它才会调用paintComponent()
。所以我可以在 paintComponent
中编写自定义代码。
最佳答案
Swing 调用 paintComponent()
面板必须绘制(paint)时的方法。我认为在面板可见之前它不会调用它。
也就是说,您的面板在添加到 GUI 后应该立即处于可绘制状态。所以 paintComponent()
方法应该通过简单地检查列表是否不为空(并且不为空)来处理尚未添加图片的情况:
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
if (pics_to_be_drawn != null && !pics_to_be_drawn.isEmpty()) {
g.drawImage(pics_to_be_drawn.get(0).Get_the_buf_img() , 41, 41, 59, 59, Color.black, null);
}
}
旁注:我会将列表初始化为 Collections.emptyList()
或 new ArrayList<>()
,这将避免检查 null。我也会尊重 Java 命名约定:类名和变量名中没有下划线,驼峰式。
关于java - 为什么在创建JPanel 类对象时,自动调用了paintComponent 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11312681/