java 不知道怎么调用paint方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5472542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:16:46  来源:igfitidea点击:

Dont know how to call paint method

javaswing

提问by Conor

Hi i want to know how to call the paint method...

嗨,我想知道如何调用paint方法...

I am a novice programmer and am really just experimenting with things like paint.

我是一名新手程序员,我真的只是在尝试绘画之类的东西。

The program i am trying to make is the game where there are 3 rungs and the aim of the game is to move different sized disks from the left/right rung to the right/left rung.

我正在尝试制作的程序是有 3 个梯级的游戏,游戏的目的是将不同大小的磁盘从左/右梯级移动到右/左梯级。

here is my code(no where near finished give me a break):

这是我的代码(还没完成就让我休息一下):

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int amount = 0;

    // get the amount of rectangles to draw to represent disks
    while (amount <= 1 && amount >= 5) {
        System.out.print("Please enter amount of discs to use(less than 7 more than one).");
        amount = scan.nextInt();            
    }
}

public void paint(Graphics g) {
    // draw a certain amount of rectangles in ascending order
    if (amount <= 1 && amount >= 5) {
        for (int i = 0; i < amount; i++) {
            g.fillRect(220 - (20 * i), 200 + (10 * i), 100 - (20 * i), 20);
        }
    }
}

回答by Ats

The paint method will be called for the first time upon creation of the object.

绘制方法将在创建对象时第一次被调用。

To force the paint()method to be called again you can either call update(Graphics g)if you want to pass in a new Graphicsobject, but normally I would suggest using repaint()method, since this way it will be scheduled to be called asap.

要强制paint()再次调用该方法,您可以在update(Graphics g)要传入新Graphics对象时调用,但通常我会建议使用repaint()方法,因为这样会安排尽快调用它。

回答by Aaron Digulla

You don't need to call it. Instead, you should use the main loop which Java creates for you.

你不需要调用它。相反,您应该使用 Java 为您创建的主循环。

The usual approach is to extend JPanel(see this question: How to make canvas with Swing?) and override the paint()method.

通常的方法是扩展JPanel(参见这个问题:如何使用 Swing 制作画布?)并覆盖该paint()方法。

Now create a JFrame, add the new UI component to it and open the frame. Java will then make sure it gets rendered.

现在创建一个JFrame,向其中添加新的 UI 组件并打开框架。然后 Java 将确保它被呈现。

回答by Kry?tof ?ehá?ek

I am not expert or something else to teach others but you need to put your code to be painted to paintComponent(Graphics g)method instead of paint and then call repaint method.

我不是专家或其他教别人的东西,但您需要将要绘制的代码放入paintComponent(Graphics g)方法而不是绘制,然后调用重新绘制方法。