我有一个简单的例子,应该创建一组绿球,而只是创建一个。我想创建一个ArrayList来保存球,但有些事情是错误的。请帮忙。
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.ArrayList;
import java.util.Random;
import javax.security.auth.x500.X500Principal;
import javax.swing.*;
public class MyBall extends JPanel{
Random rand = new Random();
int xr = rand.nextInt(400);
int yr = rand.nextInt(400);
int size = 10 ;
int x = xr ;
int y = yr ;
Ellipse2D.Double ball = new Ellipse2D.Double(0, 0, 30, 30);
ArrayList<Bubbles> balls = new ArrayList<Bubbles>();
Bubbles blobsOb = new Bubbles(x, y , size , Color.GREEN);
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 =(Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.BLUE);
g2.fill(ball);
g2.setColor(Color.green);
for (int j = 0 ; j < 10 ; j++)]{
for(int i = 0 ; i < 10; i++){
balls.add(blobsOb);
g.setColor(Color.green);
g.fillOval(x, y, size, size);
}
}
}
}
//SECOND CLASS
import javax.swing.*;
public class Main {
public static void main(String[] args) {
MyBall p = new MyBall();
JFrame f = new JFrame();
f.add(p);
f.setVisible(true);
f.setLocation(200,200);
f.setSize(400, 420);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
//Third Class
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
// this class is for the properties of green balls
public class Bubbles extends Component {
public int x;
public int y;
public int size;
public Color color;
public static Bubbles blob = new Bubbles(250,250,100,Color.BLUE);
Bubbles(int x, int y, int size, Color c){
this.x = x;
this.y = y;
this.size = size;
this.color = c;
}
public void paint(Graphics g){
g.setColor(color);
g.fillOval(x, y, size, size);
}
}
答案 0 :(得分:2)
您需要在每个周期中创建新实例
for(int j = 0; j < 10; j++){
for(int i = 0 ; i < 10; i++)
{
// ...
balls.add(new Bubbles(xr, yr , size , Color.GREEN));
}
}
答案 1 :(得分:1)
我想创建一个数组列表,其中包含绿球但问题 我只得到一个绿球而不是(10)或更多
首先,这应该在循环中:
Bubbles blobsOb = new Bubbles(x, y , size , Color.GREEN);
然后你还需要在循环中插入下面的代码,以确保在每次迭代时都有一个新生成的随机值。
int xr = rand.nextInt(400);
int yr = rand.nextInt(400);
int size = 10;
int x = xr ;
int y = yr ;
示例:
for(int j = 0; j < 10; j++){
for(int i = 0 ; i < 10; i++)
{
int xr = rand.nextInt(400);
int yr = rand.nextInt(400);
int size = 10;
Bubbles blobsOb = new Bubbles(xr, yr , size , Color.GREEN);
balls.add(blobsOb);
g.setColor(Color.green);
g.fillOval(x, y, size, size);
}
}
在将所有组件添加到.setVisible(true)
后,您应始终致电frame
。
MyBall p = new MyBall();
JFrame f = new JFrame();
f.add(p);
f.setLocation(200,200);
f.setSize(400, 420);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
最后但并非最不重要的是,您已将所有生成的Bubble
对象添加到ArrayList ArrayList<Bubbles> balls = new ArrayList<Bubbles>()
中,但是,您还没有使用balls
ArrayList。