如何在循环中使用paintComponent?

问题描述 投票:0回答:1

我正在尝试使用paint component方法绘制许多形状,但是我得到了一个不理想的结果。所以......几秒钟后,我的画面是白色的,在'Draw'== 0之后它会在一瞬间显示我的所有形状。我想绘制一个形状,然后等待500毫秒,然后绘制另一个形状而不删除前一个形状。

public package GUI;

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


public class okno3 extends JPanel{
String sb="";
int pozx,pozy,pozx2,pozy2,r,s,krztalt;
Color c;
int Draw = 3;

public static void main(String args[]){
    JFrame Frame = new JFrame();
    okno3 okno = new okno3();
    Frame.setSize(768,768);
    Frame.setTitle("Projetk 3");
    Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Frame.setVisible(true);
    Frame.add(okno);
}

public void paintComponent(Graphics g) {
    g.setColor(Color.BLACK);
    g.fillRect(0, 0, getWidth(), getHeight());
    g.setColor(getForeground());

    while(this.Draw>0) {
        this.Draw--;
        this.c = new Color((int)(Math.random()*255), (int)(Math.random()*255), (int)(Math.random()*255));
        g.setColor(c);
        this.pozx = (int)(getWidth()*Math.random());
        this.pozy = (int)(getHeight()*Math.random());
        this.pozx2 = (int)(getWidth()*Math.random());
        this.pozy2 = (int)(getHeight()*Math.random());
        this.r =(int)(Math.random()*75)+25;
        this.s =(int)(Math.random()*75)+25;

        this.krztalt = (int)(Math.random()*3)+1;

        switch(krztalt) {
            case 1:
                g.drawOval(pozx, pozy, r, s);
            break;
            case 2:
                g.drawRect(pozx, pozy, r, s);
            break;
            case 3:
                g.drawLine(pozx, pozy, pozx2, pozy2);
            break;
        }
        try{
            FileWriter fstream = new FileWriter("Wynik.txt");
            BufferedWriter out = new BufferedWriter(fstream);
            String sb = krztalt + " " + pozx + " " + pozy + " " + r + " " + s + " " + c;
            this.sb = sb + "\n" + this.sb;
            fstream.write(this.sb);
            fstream.close();

            out.close();
            }
        catch (Exception e){
            System.out.println("Error: " + e.getMessage());
        }
        try{
            Thread.sleep(500);
        }

        catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}
}
java swing loops jpanel paintcomponent
1个回答
1
投票

不要睡在paintComponent方法或在EDT中运行的任何其他方法。 EDT(事件调度线程)是一个单线程,用于处理事件和其他顺序任务,如绘画。因此,在您离开paintComponent之前,您的所有更改都不会显示。

你需要在paintComponent之外进行所有计算,然后每500毫秒,调用repaint()并让paintComponent重新绘制它们。最好使用Swing timer在重新调用之间等待。

查看Java教程中的Custom Painting并搜索此站点以获取有关绘制和事件调度线程的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.