我正在製作一個雨模擬器。我的想法是,每一滴都應該是一個對象,但由於某種原因,它們不會顯示在JFrame上。如果我更改矩形的座標值,但是如果我隨機化數字,則不會。什麼導致對象不出現?Java - 對象的隨機放置
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Rain extends RainDrop implements ActionListener{
//Change the following 2 lines of variables to change the graphics
static int width = 1000, height = 600;
int dropAmount = 650, speed = 10;
Timer tm = new Timer(speed, this);
RainDrop[] RainDrop = new RainDrop[650];
public Rain(){
for(int i = 0; RainDrop.length > i; i++){
RainDrop[i] = new RainDrop();
RainDrop[i].generateRain();
add(RainDrop[i]);
}
repaint();
}
public void paintComponent(Graphics g){
tm.start();
}
public void actionPerformed(ActionEvent e){
repaint();
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setLocation(100, 100);
f.setSize(width, height);
f.setTitle("Rain");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Rain Rain = new Rain();
f.add(Rain);
f.setResizable(true);
f.setVisible(true);
}
}
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
。
public class RainDrop extends JPanel{
//Drop [0] is used to store x values
//Drop [1] is used to store y values
//Drop [2] is used to store height values
//Drop [3] is used to store width values
//Drop [4] is used to store velocity values
private int[] Drop = new int [5];
private int width = 1000, height = 600;
public RainDrop(){
}
public int[] generateRain(){
Drop [0] = (int) (Math.random() * width);
Drop [1] = (int) (Math.random() * height);
Drop [2] = (int) (Math.random() * 13);
Drop [3] = (int) (Math.random() * 4);
Drop [4] = (int) (Math.random() * 6);
if(Drop [2] < 5) Drop [2] += 9;
if(Drop [3] < 3) Drop [3] += 3;
if(Drop [3] == 5) Drop [3] = 4;
if(Drop [4] < 3) Drop [4] += 3;
return Drop;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(Drop [0], Drop [1], 5, 20);
}
}
「generateRain」方法返回一個數組,其中包含x和y等值。不應該paintComponent使用這些值,因爲我已經使用Drop [0]和Drop [1]作爲x和y。 –
我會如何畫他們? –
您的繪畫組件方法確實使用這些值。這就是爲什麼我要說這種方法 – mike