简体   繁体   中英

java.lang.NullPointerException when drawOval in JPanel

I am tryng to draw lines in a program and I constantly get this error.. What I am doing is the following: I have a JFrame with a BoxLayout(in the Y_AXIS), and inside this frame I have 6 JPanel one below the other. In the first 2 panels I have some JLabels and JTextFields, and I would like to draw the lines in the third JPanel and I did this:

public void Dibujar(int vidas){ Graphics graf = panel3.getGraphics(); if(vidas == 6){ graf.drawOval(10, 10, 30, 30); } else{ graf.drawOval(10, 10, 60, 60); } }

But doing this I get the NullPointerException, instead of this I tried using the method paintComponent that it works but it draws below all the Jpanels and not exactly the Jpanel3.

If you need to explain something else just tell me. Thank you very much in advance.

Call this method in your Panel3 section of things. You want to paint a specific component .

@Override
class PaintExtension extends JComponent
{
    public void paintComponent(Graphics g)
    {
       int vidas = GetVidas(); //Make a method to get the vidas
       super.paintComponent(g);
       if(vidas == 6)
       {
          g.drawOval(10, 10, 30, 30);
       } 
       else
       {
          g.drawOval(10, 10, 60, 60);
       }

    }
}

In GUI:

panel3.add(new PaintExtension());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM