java - 如何在循环中使用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();
}
}
}
}
解决方案
推荐阅读
- python - system() 在 C 中调用的 Python 脚本无法将变量发送到文件
- django - Django 聚合函数是否使用索引?
- r - 计算列中出现的条纹
- node.js - 如何授权 HTTP POST 请求以使用 REST API 执行数据流模板
- react-native - React Native Expo localhost请求在android模拟器上不起作用
- excel - VBA 根据列表中的文件名导入工作表
- node.js - 如何间歇性地检查已添加到 nodejs Google Tasks API 中任务列表的新任务?
- java - Java ME SDK 平台检测失败 - Netbeans
- entity-framework - 如何解决:只有在 .Join with .Include 之后,我才会收到“No coercion operator”错误
- sml - 你如何做模式匹配是标准 ML?