I'm working on an app where I draw everything pixel by pixel. During the process, I noticed that the paintComponent()
method of a certain JPanel
is called twice. So I created the following MCVE to figure out whether it has something to do with the other components being drawn to the screen, or if it's just a standalone issue:
App.java
public class App {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MainFrame("Paint test"));
}
}
MainFrame.java
public class MainFrame extends JFrame {
private Board mBoard;
public MainFrame(String title) {
super(title);
setMinimumSize(new Dimension(400, 400));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new BorderLayout());
mBoard = new Board();
add(mBoard, BorderLayout.CENTER);
setVisible(true);
}
}
Board.java
public class Board extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("CALLED");
}
}
But the console log shows "CALLED"
twice.
I'm specifically interested in paintComponent()
since it's the method where all of the app's magic works, so I need to control each draw cycle.
What are the reasons behind this double call to paintComponent()
?
Is there another way I could do my drawings some other way once ? (I mean, not in paintComponent()
, if it would be called twice no matter what)