简体   繁体   English

如何使用重画来调用Java paintComponent

[英]How to call java paintComponent using repaint

In this video drawing() method is called in main class. 视频中,在主类中调用了drawing()方法。 When we remove drawing() in the main method it still draws the shape. 当我们在main方法中删除drawing() ,它仍会绘制形状。 How can we avoid this situation ? 我们如何避免这种情况?

shapes class: 形状类别:

import java.awt.*;
import javax.swing.*;
public class shapes{
public static void main(String[] args){
    JFrame frame = new JFrame("Test");
    frame.setVisible(true);
    frame.setSize(400,200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    draw object = new draw();
    frame.add(object);

    object.drawing();
    }

}

Draw class: 绘画课:

import java.awt.*;
import javax.swing.*;

public class draw extends JPanel{
public void drawing(){
    repaint();
}
public void paintComponent(){
  super.paintComponent(g);
  g.setColor(Color.BLUE);
  g.fillRect(10,15,100,100);
  }
}

There are some minor issues with the code, but I assume that it's only a small snippet for demonstration purposes. 该代码有一些小问题,但我认为这只是一小段用于演示目的。 For details, have a look at Performing Custom Painting . 有关详细信息,请参见“ 执行自定义绘画”

Actually, this tutorial would also answer your question, but to summarize it: 实际上,本教程也可以回答您的问题,但总结一下:

The paintComponent method will be called automatically, "by the operating system", whenever the component has to be repainted. 每当必须重新绘制组件时,都会自动“通过操作系统”调用paintComponent方法。 The call to repaint() only tells the operating system to call paintComponent again, as soon as possible. 调用repaint()仅告诉操作系统尽快再次调用paintComponent So you can call repaint() to make sure that something that you canged appears on the screen as soon as possible. 因此,您可以调用repaint()来确保您所伪造的内容尽快出现在屏幕上。

If you explicitly want to enable/disable certain painting operations, you can not influence this by preventing paintComponent from being called. 如果您明确希望启用/禁用某些绘画操作,则无法通过阻止调用paintComponent来影响此操作。 It will be called anyhow. 无论如何,它将被称为。 Instead, you'll introduce some flag or state indicating whether something should be painted or not. 相反,您将引入一些标志或状态,以指示是否应该绘制某些内容。

In your example, this could roughly be done like this: 在您的示例中,可以大致这样做:

import java.awt.*;
import javax.swing.*;

public class Draw extends JPanel{
    private boolean paintRectangle = false;

    void setPaintRectangle(boolean p) {
        paintRectangle = p;
        repaint();
    }

    @Override
    public void paintComponent(){
        super.paintComponent(g);

        if (paintRectangle) {
            g.setColor(Color.BLUE);
            g.fillRect(10,15,100,100);
        }
    }
}

You can then call the setPaintRectangle method to indicate whether the rectangle should be painted or not. 然后,您可以调用setPaintRectangle方法以指示是否应绘制矩形。

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

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