Java's getGraphics() returns null pointer problem

When typing the code in the Java book that manipulates the thread's automatic line segment (an example in the thread's sleep) , compile time

Graphics graphics=getGraphics()

graphics.setColor(getC());

A null pointer exception is generated.

Some people on the Internet say that the graphics context of the component, if it does not, returns null, so before our graphical interface is not displayed, getGraphics() returns null

Look at this program again: the class that inherits JFrame first initializes the constructor ( Graphics graphics=getGraphics() in the constructor ), and then calls the init() function to set setVisible(true); therefore, getGraphics() returns null .

How to solve it, I searched online for a long time and couldn't find it.

Since this can't put setvisible(true) before Graphics graphics=getGraphics(), then I can wait until the graphics is not empty after you setvisible(true), so I added an if statement:

Graphics graphics=getGraphics();
if(graphics!=null) {
    graphics.setColor(getC());
    graphics.drawLine(x, y, 100, y++);
    if(y>=80) {
    	y=50;
    }
}
problem solved!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324439865&siteId=291194637