gpt4 book ai didi

java - UI 不是创建形状

转载 作者:行者123 更新时间:2023-11-29 04:31:39 25 4
gpt4 key购买 nike

我有一个简单的例子,它应该创建一组绿球,但实际上只创建了一个。我想创建一个 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);
}

}

最佳答案

你需要在每个循环中创建新的实例

for(int j = 0; j < 10; j++){

for(int i = 0 ; i < 10; i++)
{
// ...
balls.add(new Bubbles(xr, yr , size , Color.GREEN));

}

}

关于java - UI 不是创建形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43547931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com