I'm currently working on a simple game in java, representative of the DOS game Gorillas.bas. I'm creating an arraylist to store the individual buildings do to collision checking and whatnot, but Eclipse is giving me an error no matter how I go about it. Here is what i've got for the arraylist.
ArrayList<Rectangle> Buildings = new ArrayList<Rectangle>();
Point build1 = new Point(75,30);
Rectangle building1 = new Rectangle(build1, BUILDING_WIDTH, 150);
Buildings.add(Rectangle building1);
The error is on the .add() method, it tells me that the method needs a body instead of a semicolon. What does this mean? Is eclipse not recognizing the .add()?
EDIT: A bit of the code around it as requested; doesn't appear to have any syntax errors.
public double bananaX = 85;
public double bananaY = 292;
public double bananaDX = 1;
public double bananaDY = 1;
public double power = 0;
public double direction = 0;
public double rise;
public double run;
Point start = new Point(0,0);
Point finish = new Point(0,0);`
ArrayList<Rectangle> buildings = new ArrayList<Rectangle>();
Point build1 = new Point(75,350);
Point build2 = new Point(225, 250);
Point build3 = new Point(325, 200);
Point build4 = new Point(425, 200);
Point build5 = new Point(525, 250);
Point build6 = new Point(675, 350);
Rectangle building1 = new Rectangle(build1, BUILDING_WIDTH, 150);
buildings.add(building1);
public void power(Point start, Point finish)
{
int power = 0;
power = (int)start.distanceTo(finish);
}
public void direction(Point start, Point finish)
{
double direction = 0;
rise = (finish.y - start.y)*-1;
run = (finish.x - start.x)*-1;
direction = rise/run;
bananaDX = run/10;
bananaDY = (rise/10);
System.out.printf("rise = %f\nrun = %f\ndirection = %f\n\n ",rise, run, direction);
}
You just need to have:
Buildings.add(building1);
Since building1 is already a Rectangle. You have already created the Rectangle object above it so you only need to use the variable itself because it is of the correct type.
Edit: You should probably also rename Buildings buildings to avoid any confusion. When you name a variable with a capital letter it looks like a type and not a variable.
Edit2: Based on the code you provided, you need to have buildings.add(building1); inside of a method of some sort. You should create an initialize method that gets called at the start if you want to have it added in at the beginning.
Don't double up on Rectangle.
Buildings.add(building1);
Related
I have been messing around with javafx for practice and ran across something I couldn't figure out. I want to put a varying number of rectangles into an arraylist. Right now, instead of that, I am storing each rectangle as an double array (double[]) of the various properties, then setting a base rectangle to those values and returning that.
public class example{
Rectangle myRectangle = new Rectangle(0,0,25,25);
ArrayList<double[]> rectangles = new ArrayList();
double[] tempArray = [0,0];
public void addRect (double x, double y){
this.tempArray[0] = x;
this.tempArray[1] = y;
this.rectangles.add(this.tempArray);
};
public Rectangle getRect (int id){
this.myRectangle.setX(this.rectangles.get(id)[0]);
this.myRectangle.setY(this.rectangles.get(id)[1]);
return(this.rectangle);
};
}
In this example, when I call getRect, it sets the x and y of the base rect, then returns that rect. This works, but I am wondering if there is a way to store multiple instances of Rectangle in the ArrayList. The main issue I saw doing this is the fact that you have to name the instance(in the example above, myRectangle). I imagine that if there is a way around this issue, it would be to name the instance based on a string, in other words:
Rectangle "myRectangle" = new Rectangle();
which is not possible, as far as I know.
I am fairly new to Javafx and Java in general so if there is anything else off with my code feel free to correct that. Thanks!
You just need to make an ArrayList<Rectangle> and add rectangles to it.
public class Example {
private List<Rectangle> rectangles = new ArrayList<>();
public void addRectangle(double x, double y, double width, double height) {
rectangles.add(new Rectangle(x, y, width, height));
}
public Rectangle getRectangle(int index) {
return rectangles.get(index);
}
}
You should note that your original code really doesn't work as expected at all. For example, try:
// please do NOT name classes with lower case...
example e = new example();
e.addRectangle(0, 0);
e.addRectangle(100, 100);
Rectangle rect1 = e.getRectangle(0);
System.out.println("Rectangle 1: ["+rect1.getX()+", "+rect1.getY()+"]");
Rectangle rect2 = e.getRectangle(1);
System.out.println("Rectangle 2: ["+rect2.getX()+", "+rect2.getY()+"]");
// but:
System.out.println("Rectangle 1: ["+rect1.getX()+", "+rect1.getY()+"]");
// oops.
System.out.println("Rectangle 1 and 2 are the same: " + (rect1==rect2) );
I a working on a program for a simple game and we are told to add something like a start menu. I have the game working by itself to where I click run, and the game pulls up in a window, but now I need to add the start menu which I am having quite a hard time doing and don't know how to get it working properly. The game I am doing is Asteroids.
The way I have it now is that the game appears on a JFrame right from the start. Since the game appears from the start, I tried making a JButton that when clicked initializes the value of a boolean variable that determines the status of the game equal to true. Here is the code I got:
public Asteroids()
{
ast = new ArrayList<Asteroid>();
aliveAsteroids = NUM_ASTEROIDS;
bullets = new Bullet[NUM_BULLETS];
ship = new Ship();
g2d = null;
gameButton = new JButton("Start");
gameButton.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
gameRunning = true;
}
});
JPanel buttonPanel = new JPanel (new FlowLayout());
buttonPanel.add(gameButton);
frame = new JFrame("Asteroids");
identity = new AffineTransform();
rand = new Random();
frame.setSize(FRAMEWIDTH, FRAMEHEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(buttonPanel);
frame.add(this);
frame.setVisible(true);
}
public static void main(String [] args)
{
Asteroids game = new Asteroids();
if(gameRunning == true)
{
game.go();
}
}
public void go()
{
//set up the ship
ship.setX(FRAMEWIDTH / 2);
ship.setY(FRAMEHEIGHT / 2);
//set up the bullets
for (int n = 0; n < NUM_BULLETS; n++)
{
bullets[n] = new Bullet();
}
//set up the asteroids
for (int n = 0; n < NUM_ASTEROIDS; n++)
{
Asteroid a = new Asteroid();
a.setX((double)rand.nextInt(FRAMEWIDTH)+20);
a.setY((double)rand.nextInt(FRAMEHEIGHT)+20);
a.setMoveAngle(rand.nextInt(360));
double ang = a.getMoveAngle() - 90;
a.setVelX(calcAngleMoveX(ang));
a.setVelY(calcAngleMoveY(ang));
ast.add(a);
}
addKeyListener(this);
requestFocusInWindow();
gameloop = new Thread(this);
gameloop.start();
}
For some reason this is not working the way I want it to and I don't understand why. Some things I try give me a NullPointerException. For the record, I know what a NullPointerException is and what it means for something to be null, but I am just not sure why I am getting one in this instance. Other things I try pull up the frame but with nothing on it even and throws a bunch of exceptions even though it should have a button.
EDIT: The exceptions that appear are Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at game.Asteroids.drawBullets(Asteroids.java:176)
at game.Asteroids.paintComponent(Asteroids.java:148)
Another question I have is about the line that says frame.add(this). What exactly is this? I know this is a keyword that can be used to initialize instance variables that have the same name as a parameter, for instance this.width = width;. But when I see this by itself in this context, I have no clue what it is referring to. So that whole line right there, I have no idea what it does. All I know is that it adds something to the frame. What that something is is beyond me.
I was wondering if anyone could help explain to me what is going on and why my program is not working correctly and maybe offer some advice/tips on how to get on the right track? I would greatly appreciate any and all help.
class anyName
{
int Tcol = 0;
int fc = 0;
int x = 0;
float randx = (random(1, 1000));
float randy = (random (0, 600));
int Tsizes = 1;
{
if (fc >= x) { //Random Ellipse 3
stroke (Tcol);
fill (Tcol);
ellipse (randx, randy, Tsizes, Tsizes);
}
}
}
anyName ranx1 = new anyName();
ranx1.x = 100;
Hi, I am trying to add a class/object to my code and it is not working. This is the class I have so far, but when I instantiate one object from that class (ranx1), and then try change one of the variables inside it (x), it says there is a error. Is there anything I need to change? I would really appreciate any help.
Since I instantiated an object from that class, how would I change the variables for the new object? For example, if in the class x = 0, then I made a copy and this time I want x to = 100, but all the other variables such as Tcol and fc to stay the same. I know this is possible because my teacher taught it, but it is not working right now for me.
I am a really newby programmer, so I think this should be easy for someone to answer.
If you want the entire code, please put your email in the answer, so that I can email the entire thing to you.
ranx1.x = 100;
You need a setter in your anyName-class. And then you call the setter:
public void setX(int x) {
this.x = x;
}
and
ranx1.setX(100) for example.
I am working on a Fluid Mechanics problem and I decided to solve the problem using Java instead of excel because I just wanted the experience. I have been stuck on this one part for the past 4 hours though. I have an array I made in one class and I need to get all that data over to another class so that I can graph it. At this point I am really just looking for the answer. My mind is shot right now and I just want to get this done with.
I have found others with similar problems, but I can not make sense of the solutions that they were given and right now my brain is fried, which is why I would prefer if someone were able to just show me exactly what to type, but any help is appreciated.
public class Eight_c {
public static void main(String [] args) {
Eight_c ball = new Eight_c();
...
int count = 0;
double[] y = new double[101];
double[] x = new double[101];
// Calculates the Distance the ball has traveled using increments of .1s
for(double t = 0; t<=time; t=t+.1) {
y[count] = t;
x[count] = d;
V1 = ball.Velocity(a, V2, dt);
Fd = ball.Drag_Force(V2);
a = ball.Acceleration(Fd, m);
d = ball.Distance(V2, a, dt) + d;
...
Above is where I have created the two arrays, x and y.
Below is where they need to go.
public class Graph {
public static void main(String [] args) {
double [] x;
double [] y;
// create your PlotPanel (you can use it as a JPanel)
Plot2DPanel plot = new Plot2DPanel();
// add a line plot to the PlotPanel
plot.addLinePlot("Distance vs Time", x, y);
// put the PlotPanel in a JFrame, as a JPanel
JFrame frame = new JFrame("a plot panel");
frame.setContentPane(plot);
frame.setVisible(true);
}
}
main() is the entry point of a program. You can't have 2 entry points. So, you need the main method of the first class to call the method of the second class, and give it x and y as arguments:
public class Graph {
public void render(double[] x, double[] y) {
// create your PlotPanel (you can use it as a JPanel)
Plot2DPanel plot = new Plot2DPanel();
// add a line plot to the PlotPanel
plot.addLinePlot("Distance vs Time", x, y);
// put the PlotPanel in a JFrame, as a JPanel
JFrame frame = new JFrame("a plot panel");
frame.setContentPane(plot);
frame.setVisible(true);
}
}
and in the main method of Eight_c:
// create a Graph object:
Graph graph = new Graph();
// ask it to render x and y:
graph.render(x, y);
I find it quite strange to start using Swing if you don't know what methods and objects are, and how to pass arguments to methods. That's a bit like trying to fly an Airbus when you have not learnt how to walk yet.
Read an introductory book about Java and programming in general. Exercise and practice with simple, console-based programs. Then only start using Swing.
I have created a java program of which starts with 1 vertex and from there it adds one vertice and 2 edges per cycle. It uses the Static Layout
Layout<Number, Number> staticLayout = new StaticLayout<Number, Number>(g, layout);
vv = new VisualizationViewer<Number, Number>(staticLayout, new Dimension(550, 550));
This is going to sound very un-technical, but the graph just doesn't look random enough, basically what i mean by this, is that every time it gets run they always seems to cluster a lot all the way around the edges of the graph, while very few get anywhere near the center. My program typically uses 100 generated verties and i will end up with half a dozen in the center and the others all round the edges.
Below is a random example that i just created just now.
Perhaps if someone could confirm that this is actually random, or if not if there is a way to get around this problem or if I've set something up wrong. As i wish to have the nodes as random as possible.
Any help would be appreciated.
Thanks
Below is the relevant code to the applet. involving its set up.
public class AnimatingAddNodeDemo extends JApplet {
//create a graph
Graph<Number, Number> ig = Graphs.synchronizedUndirectedGraph(new UndirectedSparseMultigraph<Number, Number>());
ObservableGraph<Number, Number> og = new ObservableGraph<Number, Number>(ig);
og.addGraphEventListener(new GraphEventListener<Number, Number>() {
public void handleGraphEvent(GraphEvent<Number, Number> evt) {
//System.err.println("got " + evt);
}
});
this.g = og;
//create a graphdraw
layout = new FRLayout<Number, Number>(g);
layout.setSize(new Dimension(600, 600));
setSize(700, 700);
Relaxer relaxer = new VisRunner((IterativeContext) layout);
relaxer.stop();
relaxer.prerelax();
Layout<Number, Number> staticLayout = new StaticLayout<Number, Number>(g, layout);
vv = new VisualizationViewer<Number, Number>(staticLayout, new Dimension(550, 550));
JRootPane rp = this.getRootPane();
rp.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
getContentPane().setLayout(new BorderLayout());
}
Integer v_prev = null;
public void process() {
vv.getRenderContext().getPickedVertexState().clear();
vv.getRenderContext().getPickedEdgeState().clear();
try {
if (g.getVertexCount() < 100) {
//add a vertex
Integer v1 = nodeCount;
g.addVertex(v1);
nodeCount++;
System.out.println("adding vertex " + v1);
vv.getRenderContext().getPickedVertexState().pick(v1, true);
j.setText(myText);
// wire it to some edges
if (v_prev != null) {
Integer edge = edgeCount;
//vv.getRenderContext().getPickedEdgeState().pick(edge, true);
// let's connect to a random vertex, too!
int rand = (int) (Math.random() * (edgeCount-1)); // because there is a 0 node
while (v1.equals(rand)) {
System.out.println("avoided connecting to myself");
rand = (int) (Math.random() * (edgeCount-1)); // because there is a 0 node
}
edgeCount++;
g.addEdge(edge, rand, v1); //add an edge called var1, between the nodes var2 and var3
vv.getRenderContext().getPickedEdgeState().pick(edge, true);
System.out.println("Adding edge " + edge + " between " + rand + " & " + v1 + "()");
}
v_prev = v1;
layout.initialize();
Relaxer relaxer = new VisRunner((IterativeContext) layout);
relaxer.stop();
relaxer.prerelax();
vv.getRenderContext().getMultiLayerTransformer().setToIdentity();
vv.repaint();
} else {
done = true;
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
AnimatingAddNodeDemo and = new AnimatingAddNodeDemo();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(and);
and.init();
and.start();
frame.pack();
//frame.setVisible(true);
}
}
The reason your graph isn't random likely stems from the fact that you are passing a FRLayout to the constructor.
layout = new FRLayout<Number, Number>(g);
// ...
Layout<Number, Number> staticLayout = new StaticLayout<Number, Number>(g, layout);
You could make your own random layout class by extending AbstractLayout. But, according to the JavaDoc, StaticLayout will randomly layout nodes if you exclude the second constructor argument.
Layout<Number, Number> staticLayout = new StaticLayout(Number, Number>(g);
I Didn't get to a conclusion on whether or not it is random. So instead when i create each vertex i decided to set the particular co-ordinate of the vertex using layout.setLocation(v1, x, y)
With making x and y using math.random() and multiplying it by the width and height of my applet.
Therefore i now know that it is random.
EDIT
This actually seemed to work, however it actually did not, I had to remove the FRLayout.
It turns out FRLayout will not let you set your own locations because of what the algorithm does.
FRLayout is a force directed Layout that will reposition the vertices
according to the topology of the graph.
So i therefore changed the FRLayout to StaticLayout, removed a few things that worked only with FRLayout and it works correctly now.