draw graphics outside of paint method

会有一股神秘感。 提交于 2019-12-12 15:15:37

问题


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 ));


来源:https://stackoverflow.com/questions/20017783/draw-graphics-outside-of-paint-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!