【发布时间】: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