draw graphics outside of paint method

2019-07-05 03:47发布

问题:

private void draw_shape() {                                         
    Graphics g = getGraphics();
    g.drawLine(0, 0, 100, 100);
    repaint();
}                                        

In paint method only those graphics are drawn which is a part of paint method because of which I wanted to draw shapes outside of paint method. This code draws the line but it immediately disappeares, I don't understand why this is happening. please help

回答1:

This doens't work because you are getting the current Graphics outside of the Swing repaint thread. Basically:

  • you get the current Graphics
  • you draw something on it
  • then you call repaint() that will call the paint() of the component thus discarding all you did

To make it work you should override the paint (paintComponent for Swing) method of your object:

@Override
public void paint(Graphics g) {
  super.paint(g); // if you have children to the component
  g.drawLine(..)
}

and then just call repaint() when something has been modified.



回答2:

The line disappears because Swing (or AWT) will call paint(Graphics) or paintComponent(Graphics g) in order to pain the component.

What you need to do is to put your drawing logic on the paint(Graphics) or paintComponent(Graphics g) method. The latter is more advisable.

If you really need to draw things using another method, store an image as a class field and draw this image on the paint or paintComponent methods.



回答3:

Because the paint method also paints stuff. You should not draw graphics outside the paint method. You should instead override the paint method, like this:

@Override public void paint (Graphics g) {
    super.paint(g);
    g.drawLine(0, 0, 100, 100);
}


回答4:

Thanks for the help found the answer

BufferedImage image = (BufferedImage) createImage(300, 300);
image.getGraphics().drawLine(0, 0, 300, 300);
jLabel1.setIcon( new ImageIcon(image ));