I am building a game for a class I'm working on and I need to paint some circles and rectangles. My problem is that there will be an unknown number of each the circles and rectangles, depending on user input. For example,if the user says 5
, there will be 25
circles. What I wanted to do was make a circle class and rectangle class so I could just change the x and y coordinates using a loop.
Is it possible to make such a class "circle"
and class "rectangle"
with a parameterized constructor (x and y coordinates) to accomplish this?
FYI - This is a pegboard game where you drop a ball on the top and the ball bounces off pegs until being caught in the rectangle holders. I believe the true name of this game is called pachinko. Similar to this image, but just a rectangle instead of a triangle setup.
https://i.ytimg.com/vi/b3B8qiXyTJ8/maxresdefault.jpg
Lastly, I must use only swing
and/or javafx
(which I am unfamiliar with)
Okay Guys, I figured this one out. For what I wanted to do, I simply had needed a paintComponent() method inside another class, then made my other class Ball() use this paintComponent() by requesting a Graphics object inside a my paintBall() method's parameters, then using this graphics object to paint my Ball class object. My answer seems wordy, but look at the Ball class below and you'll get it.
package main;
import java.awt.Graphics;
public class Ball{
private int x = 5;
private int y = 30;
// This method will help to animate the current object,
// The xPos and yPos will change, then frame will be repainted
public void setPos(int xPos, int yPos)
{
x = xPos;
y = yPos;
}
public void drawBall(Graphics g)
{
g.setColor(Color.GREEN);
g.fillOval(x, y, 30, 30);
}
}
So basically, i just had to create an instance of Ball inside my main class, like so:
Ball myBall = new Ball();
myBall.drawBall(g); // where g is the graphics object from paintComponent() in the main class.