【问题标题】:How to use paintComponent in loop?如何在循环中使用paintComponent?
【发布时间】:2019-09-17 11:53:42
【问题描述】:

我正在尝试使用绘制组件方法绘制许多形状,但我得到了一个不理想的结果。所以……几秒钟后,我的框架是白色的,在'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】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-01
      • 2013-12-03
      • 2011-05-06
      相关资源
      最近更新 更多