title: Why won't JAVA Graphics draw
body: <p>I am a beginner to JAVA and I'm breaking my head on the following problem:</p>
  
  <p><strong>Why does this code not draw</strong></p>
  
  <pre><code>import ...
  
  public class tekening extends JFrame{
  
      private JPanel p;
      private Graphics g;
  
      tekening(){
  
          setLayout(new FlowLayout());
  
          p = new JPanel();
          p.setPreferredSize(new Dimension(350, 350));
          p.setBackground(Color.WHITE);
          add(p);
  
          setLocationByPlatform(true);
          setSize(400, 400); 
          setVisible(true);
          setDefaultCloseOperation(EXIT_ON_CLOSE); 
  
          g = p.getGraphics();
          g.setColor(Color.BLACK);
          g.drawRect(30, 30, 80, 40);
          g.drawLine(10, 10, 40, 50);
      }
  
  }
  </code></pre>
  
  <p><strong>And why does this code draw</strong></p>
  
  <pre><code>import ...
  
  public class tekenclasse extends JFrame implements ActionListener{
  
      private JPanel p;
      private Graphics g;
      private JButton button1;
  
      tekenclasse(){
  
          setLayout(new FlowLayout());
  
          button1 = new JButton("Knop 1");
          button1.addActionListener(this);
          add(button1);
  
          p = new JPanel();
          p.setPreferredSize(new Dimension(350, 350));
          p.setBackground(Color.WHITE);
          add(p);
  
          setLocationByPlatform(true);
          setSize(400, 400); 
          setVisible(true);
          setDefaultCloseOperation(EXIT_ON_CLOSE); 
      }
  
      public void actionPerformed(ActionEvent e){
          g = p.getGraphics();
          g.setColor(Color.BLACK);
          g.drawRect(30, 30, 80, 40);
          g.drawLine(10, 10, 40, 50);
      }
  
  }
  </code></pre>
  
  <p>For me this is completely strange. Why can't I use the Graphics inside the constructor. And why can I use it after an event. This is stupid I want to draw on immediately and I don't want to press a button.</p>