This is the java code about JPanel:
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);
}
}
As I set up the 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);
I found that the creation of Battle_field() object above will call the paintComponent automatically.
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.
p.s:
According to the official document,only if I call repaint(), it will call paintComponent(). So I can write my customized code within paintComponent.
Swing calls the
paintComponent()method when the panel must be painted. I don’t think it will call it until the panel is made visible.That said, your panel should be in a paintable state as soon as it’s added to the GUI. So the
paintComponent()method should handle the case where the pictures have not been added yet, by simply checking that the list if not null (and not empty):Side note: I would initialize the list to
Collections.emptyList()or tonew ArrayList<>(), which would avoid the check for null. I would also respect the Java naming conventions: no underscore in class and variable names, camelCasing.