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.
Related
I have two more classes that this main class is using, but I think that it can be answered without those classes because I think it is a logic problem.
I'm trying to create a JFrame that prints out a drawing. The way the API is set up, I want public Viewer to create the frame and set the title and then main to instantiate a viewer. But the way I have this set up keeps printing double the amount of frames that I need. Also, when I try to concatenate
v.setTitle(v.getTitle() + String.format(" pi = %.4f", pi));
it doesn't work. It just prints a new JFrame with just
String.format(" pi = %.4f", pi));
and the original JFrame prints its name (two separate frames). So I know it has to be a logic problem somewhere, but I can't figure it out.
import java.util.Scanner;
import javax.swing.JFrame;
public class Viewer extends JFrame{
private ControlPanel cp;
public Viewer(String name, int in){
JFrame frame = new JFrame();
frame.setSize(550, 550);
frame.setTitle("Name: " + name);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cp = new ControlPanel(in);
frame.add(cp);
frame.setVisible(true);
}
/**
* #param args
*/
public static void main(String[] args) {
int n = (int) 1e4;
System.out.println("Enter the number of runs to make <1 to 4>:");
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
int runs = in.nextInt();
if (runs > 4){
runs = 4;
}
if (runs < 1){
runs = 4;
}
for (int i = 1; i <= runs; i ++){
n = n * runs;
Viewer v = new Viewer("Trey Wilson", n);
int hits = v.cp.getHits();
double pi = 4.0 * hits / n;
v.setTitle(v.getTitle() + String.format(" pi = %.4f", pi));
v.pack();
v.setVisible(true);
v.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
}
Your code has multiple errors:
It extends JFrame and creates a JFrame object (just remove the extends JFrame from the class, it's recommended to do so)
Here lies your problem:
Viewer v = new Viewer("Trey Wilson", n);
this calls the Viewer's class constructor but the constructor itself sets it's own title, size, etc, and then you're modifying those attributes and making another call to setVisible(true) which makes this last frame visible again, so remove one or the other.
You're not placing your program on the EDT, see SwingUtilities.invokeLater() why is it needed?
See The use of multiple JFrames, Good / Bad Practice? (Bad) you should instead want to try using a single JFrame with multiple JPanels switching them with a Card Layout or using JDialogs to display / retrieve information to / from user
From your comment above:
I'm completely new to Jframe (along with java) and was given an API to follow along with. What does extends mean? I'll give it a google, but didn't know if you had an answer on how to fix it.
I recommend you to learn the OOP basics, Java concepts first before going into Java Swing which will make your learning harder because it will add more complexity to it and make it harder to you to maintain or make a quality software.
THIS SOLVES THE PROBLEM OF DOUBLE FRAME APPEARING:
So you can either take away frame.setVisible(true); in the constructor as in:
public Viewer(String name, int in){
JFrame frame = new JFrame();
frame.setSize(550, 550);
frame.setTitle("Name: " + name);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cp = new ControlPanel(in);
frame.add(cp);
}
OR Rather take away v.setVisible(true); from you main method.
I will advice you to take away frame.setVisible(true);. But depending on you requirement, choose the best for yourself.
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) );
In my main class i have built a JFrame and added functionality to a button which gets stock values from yahoos sites. Im currently storing the stock values in an arraylist and passing it to the other class, but thats not the problem. My problem is i dont know how to call the "paintComponent" method from my frame, because of the "Graphics g" variable. I think im missing the big picture here, am i on the right tracks or should i be looking to solve this problem some other way?
here is my graph class:
public class graph {
private static Main main;
public void paintComponent(Graphics g) {
Graphics2D graph2 = (Graphics2D)g;
graph2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
ArrayList<String> first = main.getFirst();
int x1 = 0;
int x2= 1;
for (String x : first) {
String[] parts = x.split(",");
int y1 = Integer.parseInt(parts[0]);
int y2= Integer.parseInt(parts[1]);
Shape drawLine = new Line2D.Float(y1, x1, y2, x2);
graph2.draw(drawLine);
}
}
}
You are not supposed to call this method by yourself. graph (which should be called Graph) has to extend a Swing component so that you just have to add it as a child of one of your containers to display it.
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);
In Java using the acm.graphics GPen is there any way to move the entire drawn sequence of lines? I've read the manual thoroughly and I'm beginning to think it's not possible which brings me to my second question. Are there any other graphics objects in Java that work very similar to a pen that can also be moved. The reason I'm asking is because I've been working on a graphing program that allows mouse gestures to be used to pan around and zoom in and out. After building functionality for implicit functions I realized simply clearing the drawing board and redrawing everything is not going to cut it anymore so I really need to work on more efficient ways to handle intermediate changes of the graph without having to recalculate everything. For example with this or similar code:
GPen p = new GPen();
p.setLocation(100,100); //places the pen on the canvas at 100, 100
p.drawLine(-50,0); //draw a line left 50 pixels
p.drawLine(50,-50); //draw a line right and up 50 pixels each
p.drawLine(0,50); //draw a line down 50 pixels
This would result in a simple right triangle who's bottom right most point is at 100, 100 on a particular canvas. What I need to do is be able to move this same drawn sequence of lines relative to one another to another origin. What I hoping for is a class that has separate methods for setLocation() and move() where setLocation() controls pen position and move() would move the entire object around.
Ok so having received almost no attention on here I've came to the conclusion that such a method just needs to be written from scratch and went ahead and did that. I'm not entirely sure how helpful posting my proprietary code would be but in the event that anybody could use it I'll post the basic idea of it. Since Pen utilities are essentially a bunch of lines and lines are a bunch of from and to's I created an object that I called FPen (for FunctionPen) that accepts the instructions for from and to. While defining FPen you pass it where to start and how far to go however many times you need and that's it. Once you've passed these instructions I created another method called returnGPen(Color c) which will on call use the instructions it has on hand and generate the desired GPen object. When you want to move the entire GPen you can then create a method called adjustOrigin(double oX, double oY); which will calculate a change from a previously recorded origin and this new one and go through the list of instructions and adjust them appropriately.
My needs for this Class are strictly for my Graphing program and are not entirely finished either but it does work for most purposes.
import acm.graphics.GPen;
import java.awt.Color;
import java.util.ArrayList;
public class FPen{
private double relativeCenterX;
private double relativeCenterY;
private ArrayList<Double> fromX = new ArrayList<Double>();
private ArrayList<Double> fromY = new ArrayList<Double>();
private ArrayList<Double> distX = new ArrayList<Double>();
private ArrayList<Double> distY = new ArrayList<Double>();
public FPen(double rX, double rY, double z){
relativeCenterX = rX;
relativeCenterY = rY;
}
public void adjustOrigin(double cX, double cY){
double changeX = relativeCenterX-cX;
double changeY = relativeCenterY-cY;
for(int i = 0; i < fromX.size(); i++){
fromX.set(i,fromX.get(i)+changeX*zoom);
fromY.set(i,fromY.get(i)-changeY*zoom);
}
relativeCenterX = cX;
relativeCenterY = cY;
}
public void clear(){
fromX.clear();
fromY.clear();
distX.clear();
distY.clear();
}
public void drawLine(double fX, double fY, double tX, double tY){
fromX.add(fX);
fromY.add(fY);
distX.add(tX);
distY.add(tY);
}
public GPen returnGPen(Color c){
GPen pen = new GPen();
pen.setColor(c);
for(int i = 0; i < fromX.size(); i++){
pen.setLocation(fromX.get(i),fromY.get(i));
pen.drawLine(distX.get(i),distY.get(i));
}
return pen;
}
}
Of course a unexpected nice thing that came out of this was the idea that I can now quickly benchmark different drawing routines by creating different methods for each and calling what I'm interested in.