首页 > 解决方案 > 如何在循环中使用paintComponent?

问题描述

我正在尝试使用绘画组件方法绘制许多形状,但我得到了一个不受欢迎的结果。所以……有几秒钟我的框架是白色的,之后'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();
        }
    }
}
}

标签: javaswingloopsjpanelpaintcomponent

解决方案


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

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

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


推荐阅读