Почему рисуется только один мяч?Там должно быть еще много - PullRequest
0 голосов
/ 31 марта 2019

Я пытаюсь создать объект ArrayList of Ball и хочу нарисовать их на экране, но рисуется только один из них, и я не знаю почему.

Класс мяча:

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.util.Random;

public class Ball extends JPanel{
    int sX,sY;
    Color color;
    int speed;
    int height;
    int width;
    int velX=0;
    int velY=0;
    Random randInt;
    JFrame window;
    public Ball(int sX,int sY,int height,int width){
        this.sX=sX;
        this.sY=sY;
        this.color=color;
        this.speed=speed;
        this.height=height;
        this.width=width;
    }
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2d=(Graphics2D)g;
        g2d.setColor(color.RED);
        Ellipse2D ellipse = new Ellipse2D.Double(sX,sY,width,height);
        g2d.fill(ellipse);

    }


    public String getCoords(){
        return "X: "+String.valueOf(sX)+" Y: "+String.valueOf(sY);
    }
}

Класс BallManager (где хранится массив объектов-шаров)

import javax.swing.*;
import java.util.ArrayList;

public class BallManager {
    ArrayList<Ball> listOfBalls;
    int width,height;
    JFrame window;
    Ball newBall;
    public BallManager(JFrame window) {
        this.listOfBalls=new ArrayList<Ball>();
        this.window=window;
        this.addBalls(100);
        //this.drawBalls();
    }
    public void addBalls(int n){

        for (int y=0;y<n;y+=20){
            for(int x=0;x<n;x+=20){
                this.listOfBalls.add(new Ball(x,y,10,10));
                drawBalls();
            }
        }
        System.out.println(listOfBalls.size());

    }
    public void drawBalls(){

        for(Ball b:listOfBalls){
            window.add(b);
            System.out.println(b.getCoords());
        }
    }
}

Основной класс:

public class Main {
    public static void main(String[] args){

        JFrameWindow j= new JFrameWindow(300,500);
        BallManager bm=new BallManager(j);
    }
}

Класс окна:

import javax.swing.*;
import java.awt.*;

public class JFrameWindow extends JFrame {
    int width;
    int height;
    public JFrameWindow(int width,int height){
        super("JFrame ballssssss");
        this.width=width;
        this.height=height;
        this.setLocationRelativeTo(null);
        this.setSize(this.width,this.height);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.setVisible(true);
        this.getContentPane().setBackground(Color.orange);


    }


}

Понятия не имею, в чем проблема.Мне кажется, что шары в массиве движутся в унисон друг с другом, но я не знаю почему.

1 Ответ

3 голосов
/ 31 марта 2019

У вас есть некоторые вещи немного задом наперед:

  • Класс Ball должен не выходить из JPanel или любого другого компонента Swing.Вместо этого это должен быть логический класс, который знает местоположение, цвет шара и как его нарисовать, в методе, скажем, public void draw(Graphics g).
  • Должен быть только одинJPanel, который содержит логические Шары в ArrayList<Ball> и рисует их все в своем методе paintComponent с помощью цикла for.
  • Этот единственный JPanel должен быть добавлен в JFrame, BorderLayout.CENTER.

например,

public class Ball {
    private static final int RADIUS = 5;
    private int x;
    private int y;
    private Color color;

    // constructors

    // getters / setters

    // methods to move the ball

    // or might use Graphics2D and rendering hints to smooth drawing
    public void draw(Graphics g) {
        g.setColor(color);
        g.fillOval(x - RADIUS, y - RADIUS, 2 * RADIUS, 2 * RADIUS);
    }
}   

и

class BallPanel extends JPanel {
    private List<Ball> balls = new ArrayList<>();

    // constructor -- fill the balls list

    // other methods....

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (Ball ball : balls) {
            ball.draw(g);
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...