gpt4 book ai didi

java - 为什么在创建JPanel 类对象时,自动调用了paintComponent 方法?

转载 作者:行者123 更新时间:2023-11-29 07:13:59 27 4
gpt4 key购买 nike

这是关于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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com