问题
I have been told many times that the paint() method will be called as and when required when I extend my class to JFrame but for eg. in the code the paint method is not being called and I don't see any rectangle drawn.
I even tried to call paint method inside the constructor (which I created) and then creating an obejct for the class in main but I got a NullPointerException
import java.awt.Graphics;
import javax.swing.JFrame;
public class MyFirstDrawing extends JFrame
{
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String args[])
{
JFrame w = new JFrame("Hello World");
w.setTitle("My First Drawing");
w.setDefaultCloseOperation(EXIT_ON_CLOSE);
w.setSize(500,500);
w.setVisible(true);
}
public void paint(Graphics g)
{
g.drawRect(40, 40, 100, 200);
}
}
回答1:
You have two frames:
You extend a JFrame and override the paint() method, but that frame is never made visible so the paint() method is never invoked.
Then you create a new JFrame which you make visible, but this frame has no custom painting so you just see the frame.
In any case this is NOT the way to do custom painting. Custom painting is done by overriding paintCompnent(...)
of a JPanel and then you add the panel to the frame. Read the section from the Swing tutorial on Custom Painting for more information and working examples that you can customize.
The tutorial example will show you a better way to create your class so there is no need to extend a JFrame. Follow the tutorial example.
来源:https://stackoverflow.com/questions/44269435/java-how-and-when-exactly-is-the-paint-method-called