draw graphics outside of paint method

2019-07-05 03:08发布

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

4条回答
贪生不怕死
2楼-- · 2019-07-05 03:32

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楼-- · 2019-07-05 03:50

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.

查看更多
家丑人穷心不美
4楼-- · 2019-07-05 03:51

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);
}
查看更多
虎瘦雄心在
5楼-- · 2019-07-05 03:56

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 ));
查看更多
登录 后发表回答