简体   繁体   English

JPanel中的drawOval时java.lang.NullPointerException

[英]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. 我正在尝试在程序中画线,并且不断出现此错误。.我正在做以下事情:我有一个带BoxLayout(在Y_AXIS中)的JFrame,在这个框架内,我有6个JPanel,一个在另一个下面。 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: 在前两个面板中,我有一些JLabel和JTextFields,我想在第三个JPanel中画线,我这样做:

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. 但是这样做却得到了NullPointerException,而不是我尝试使用它可以工作的方法paintComponent,但是它绘制在所有Jpanel的下方,而不是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. 在您的Panel3部分中调用此方法。 You want to paint a specific component . 您要paint特定的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: 在GUI中:

panel3.add(new PaintExtension());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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