Why is it that only the line (0,0) - (100,100) is drawn, indicated in the overloaded paint, but the figures drawn in Main are not displayed?

As far as I understand, when repaint () in paint (Graphics g) is automatically transferred to the Graphics object. But changes to the graphics made in Main'e for some reason are not displayed.


package sandbox; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; public class Main extends JFrame{ private static final long serialVersionUID = -7362977924195873951L; MyPanel main_panel; Graphics gr; public Main() { main_panel = new MyPanel(); this.setContentPane(main_panel); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(400, 400); this.setResizable(false); pack(); gr = main_panel.getGraphics(); gr.setColor(new Color(0, 255, 255)); gr.clearRect(0, 0, 400, 400); gr.fillOval(100, 100, 100, 100); main_panel.repaint(); this.repaint(); } public static void main(String args[]) { EventQueue.invokeLater(new Runnable() { public void run() { new Main().setVisible(true); } }); } class MyPanel extends JPanel { private static final long serialVersionUID = -5120203616437379506L; MyPanel() { setPreferredSize(new Dimension(400, 400)); } @Override public void paint(Graphics g) { super.paint(g); g.drawLine(0, 0, 100, 100); } } } 

    1 answer 1

    In Swing, each component draws itself in the paintComponent (Graphics g) method. That is, when calling the repaint () method, this method will be called in which it says only about the drawn line - that which is not saved anywhere in the main method. If you want to draw on a component, store what you want to draw in a variable and pass to the paintComponent () method

    • Replacing this.repaint() with main_panel.paintComponents(gr) does nothing. Could you explain in more detail? - user211079