简体   繁体   English

在绘画方法之外绘制图形

[英]draw graphics outside of paint method

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 请帮忙

This doens't work because you are getting the current Graphics outside of the Swing repaint thread . 这样做没有用,因为你在Swing重绘线程之外获取了当前的Graphics Basically: 基本上:

  • you get the current Graphics 你得到了当前的Graphics
  • you draw something on it 你画上了什么东西
  • then you call repaint() that will call the paint() of the component thus discarding all you did 然后你调用repaint()来调用组件的paint() ,从而丢弃你所做的一切

To make it work you should override the paint ( paintComponent for Swing) method of your object: 要使其工作,您应该覆盖对象的paintpaintComponent for Swing)方法:

@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. 然后在修改某些内容时调用repaint()

The line disappears because Swing (or AWT) will call paint(Graphics) or paintComponent(Graphics g) in order to pain the component. 该行消失,因为Swing(或AWT)将调用paint(Graphics)或paintComponent(Graphics g)以使组件变形。

What you need to do is to put your drawing logic on the paint(Graphics) or paintComponent(Graphics g) method. 您需要做的是将绘图逻辑放在绘图(Graphics)或paintComponent(Graphics g)方法上。 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. 如果您确实需要使用其他方法绘制内容,请将图像存储为类字段,并在paint或paintComponent方法上绘制此图像。

Because the paint method also paints stuff. 因为paint方法也涂料。 You should not draw graphics outside the paint method. 您不应该在paint方法之外绘制图形。 You should instead override the paint method, like this: 你应该改写paint方法,如下所示:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM