I have the following Processing program:
//using Papplet instead of STDraw to visually represent my grid, created by Mahmed Ibrahim
import java.awt.Color;
import processing.core.*;
import processing.core.PApplet;
public class C4Grid extends PApplet {
PShape s;
PShape[][] circleSpaces;
boolean[][] circleSpacesFilled;
boolean[][] circleHasYelowPiece;
boolean[][] circleHasRedPiece;
final float SPACES_BETWEEN_ROWS = 110;
final float SPACES_BETWEEN_COLUMNS = 130;
public C4Grid(){}
public void setup() {
System.out.println("it got to here where it breaks");
size(1000, 1000, P2D);
// Making the shape of the grid using vertices
// so I'm manually drawing my polygon.
s = createShape();
s.beginShape();
s.fill(34, 56, 100);
s.tint(34, 56, 100);
s.stroke(0);
s.strokeWeight(5);
s.vertex(400, 400);
s.vertex(400, -440);
s.vertex(360, -440);
s.vertex(360, -400);
s.vertex(-360, -400);
s.vertex(-360, -440);
s.vertex(-400, -440);
s.vertex(-400, 420);
s.vertex(-420, 420);
s.vertex(-420, 440);
s.vertex(-360, 440);
s.vertex(-360, 420);
s.vertex(-380, 420);
s.vertex(-380, 400);
s.vertex(380, 400);
s.vertex(380, 420);
s.vertex(360, 420);
s.vertex(360, 440);
s.vertex(420, 440);
s.vertex(420, 420);
s.vertex(400, 420);
s.vertex(400, 420);
s.vertex(400, -440);
s.vertex(400, 400);
s.endShape();
System.out.println("it got to here where it breaks");
// using a 2D array to create a grid of circles
// which will represent the spaces on the grid
circleHasYelowPiece = new boolean[7][6];
circleHasRedPiece = new boolean[7][6];
circleSpacesFilled = new boolean[7][6];
circleSpaces = new PShape[7][6];
for (int row = 0; row < 7; row++) {
for (int column = 0; column < 6; column++) {
circleSpaces[row][column] = createShape(ELLIPSE, -380 + (row) * SPACES_BETWEEN_ROWS,
-370 + (column) * SPACES_BETWEEN_COLUMNS, 100, 100);
circleSpaces[row][column].disableStyle();
stroke(0);
strokeWeight(5);
circleSpacesFilled[row][column] = false;
circleHasRedPiece[row][column] = false;
circleHasYelowPiece[row][column] = false;
}
}
}
public void draw() {
translate(width / 2, height / 2);
shape(s);
for (int row = 0; row < 7; row++) {
for (int column = 0; column < 6; column++) {
shape(circleSpaces[row][column]);
}
}
}
public boolean piecePlaced(int column, Color pieceColor) {
column = column - 1; // the choice are form 1-7 but in an array its 0-6;
boolean moveDone = false;
int i = 5;
Color red = new Color(255, 0, 0);
while (i >= 0) {
if (circleSpacesFilled[column][i] == false) {
circleSpacesFilled[column][i] = true;
if (pieceColor.equals(red)) {
circleHasRedPiece[column][i] = true;
circleSpaces[column][i].fill(255, 0, 0);
circleSpaces[column][i].tint(255, 0, 0);
} else {
circleHasYelowPiece[column][i] = true;
circleSpaces[column][i].fill(255, 255, 0);
circleSpaces[column][i].tint(255, 255, 0);
}
return true;
}
}
return false;
}
}
When I run it, I get this NullPointerException. Notice that the exception is coming from within Processing's libraries - it's not directly caused by my own code!
The 3 lines that are suspect are:
currentGame = new C4Game(player1Is,player2Is,player1Color,player2Color);
theGrid = new C4Grid(); theGrid.setup();
s= createShape(); near the top of setup()
currentGame, theGrid, and s are all non-null (I've checked countless times).
Even when I test each line in isolation, I get an error in anything that related to the PShape class. I got rid of every PShape object and it worked, but is there a way to fix it so I can use PShape as part of my code?
When I run your code, I don't get a NullPointerException. I get an error that says this:
When not using the PDE, size() can only be used inside settings().
Remove the size() method from setup(), and add the following:
public void settings() {
size(1000, 1000, "processing.opengl.PGraphics2D");
}
And the error says it all. When you're using Processing as a library, you can't call the size() function from the setup() function. Call it from the settings() function instead.
If I make that change, your code runs fine:
Related
I'm working on a pathfinding algorithm in processing. If I don't draw a line that crosses the path between the green and the red dot, it works, but if I do, I've got a problem, that if I call a function, the program does absolutely nothing but freezes, and I have no idea why. The pixelss stores what you draw, and there are all kinds of stuff, that don't matter at this problem.
When you paste it to processing, press ctrl+t to auto-format it so you can understand it better, but I'd bet it's a newbie issue.
int[][] pixelss = new int[500][500];
void setup() {
background(255);
size(500, 500);}
int[][] badcoos = new int[500][500];
void golinego() {
stroke(200, 200, 255);
line(30, 30, 470, 470);
int j = 30;
int i = 30;
while (dist(i, j, 470, 470) > 10) {
stroke(0, 0, 180);
circle(i, j, 1);
if (pixelss[i+1][j+1]==0) {
i++;j++;}
if (pixelss[i][j]==1) {
if (pixelss[i][j+1]==1) {
if (pixelss[i+1][j]==0) {
i++;}
} else if (pixelss[i+1][j]==1) {
if (pixelss[i][j+1]==0) {
j++;}
} else {
i-=1;
j-=1;}}}}
void draw() {
stroke(0, 255, 0);
fill(0, 255, 0);
circle(30, 30, 10);
stroke(255, 0, 0);
fill(255, 0, 0);
circle(470, 470, 10);
if (mousePressed == true) {
try {
stroke(0);
fill(0);
circle(mouseX, mouseY, 2);
pixelss[mouseX][mouseY] = 1;
pixelss[mouseX+1][mouseY] = 1;
pixelss[mouseX-1][mouseY] = 1;
pixelss[mouseX][mouseY+1] = 1;
pixelss[mouseX][mouseY-1] = 1;
pixelss[mouseX+1][mouseY+1] = 1;
pixelss[mouseX-1][mouseY+1] = 1;
pixelss[mouseX+1][mouseY-1] = 1;
pixelss[mouseX-1][mouseY-1] = 1;
}catch(ArrayIndexOutOfBoundsException e) {}}}
void keyPressed() {
if (key=='r') {
pixelss = new int[500][500];
badcoos = new int[500][500];
background(255);}
if (key==' ') {
golinego();}
if (key=='d') {
background(0);
for (int i = 0; i < 500; i++) {
for (int j = 0; j < 500; j++) {
if (pixelss[i][j]==1) {
stroke(255);
circle(i, j, 1);}}}}}
The program is getting caught in your while loop.
You can see this if you print out the values of i and j inside the loop. They never meet the condition to escape the loop, so that chunk of code runs repeatedly with no change.
while (dist(i, j, 470, 470) > 10) {
println(i, j);
// etc...
}
This hangs the app because the while loop needs to complete before the the draw function gets called again to update the screen.
It's not clear to me what you're actually doing in the while loop, but that's where you should look. Either alter your logic inside the loop, or change the condition to ensure that the code doesn't get stuck in an infinite loop.
You should at least print something when the ArrayIndexOutOfBoundsException is caught.
It looks like you are working with some kind of gui library, make sure you are doing any processing in separate thread from the gui or the gui will become unresponsive and appear to 'freeze' like you describe.
https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html
The essential question of what I am trying to ask is: How would I make a graph in which the line at y=0 is actually at y=*some number* and that as my Y increases, Java's y decreases?
I am attempting to make a line graph which documents change of populations of animals. I need to make the graph's Y=0 around the y=980 line. I also need to make something that would notice an increase in population and graph it as a decrease in y (to make the line go UP). What I'm trying to say is that I need to create a line graph that looks like a line graph.
I have attempted multiple different things, which each give me a different result based on different inputs. I have successfully created the graph that starts around the y=980 line and goes up, as shown by the image below. The method I used for this was to draw the lines (for the graph itself) and then to take the absolute value of the difference of 10 times the value minus 90, as shown by
g.drawLine((125), (y+1)*93, width, (y+1)*93);
g.drawString(Math.abs(y*10-90) + " alive", (80), (y+1)*93);
This completely works for the graph, but when trying to implement it into the graphing of the lines, I receive mixed results.
For this project, I have 3 populations: predators of my animal, prey of my animal, and my animal. I want to graph the population size of all of these. When using the previously shown method, I successfully graph the first value of the population of the predators. The other two, however, are on the opposite side of the graph from where they must be. (e.g. my animal's population size is set to start at 90, but on the graph it is around the mid-20s, as also shown by the graph below). The code I used for each of these is:
// predator animal line
g.setColor(Color.red);
g.drawLine(i*93+125, (Math.abs((predatorAnimalAmt[i]*10)-90)), (i+1)*93+125, (Math.abs((predatorAnimalAmt[i+1]*10)-90)));
g.drawLine(100, height-45, 120, height-45);
g.drawString("PREDATOR", 30, height-40);
// prey animal line
g.setColor(Color.green);
g.drawLine(i*93+125, (Math.abs((preyAnimalAmt[i]*10)-90)), (i+1)*93+125, (Math.abs((preyAnimalAmt[i+1]*10)-90)));
g.drawLine(100, height-60, 120, height-60);
g.drawString("PREY", 30, height-55);
// our animal's line
g.setColor(Color.blue);
g.drawLine(i*93+125, (Math.abs((ourAnimalAmt[i]*10)-90)), (i+1)*93+125, (Math.abs((ourAnimalAmt[i+1]*10)-90)));
g.drawLine(100, height-75, 120, height-75);
g.drawString("OUR ANIMAL", 30, height-70);
Here is my code in this class (there are other classes accessible in my github page)
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.image.BufferStrategy;
import java.util.ArrayList;
import java.util.Random;
// ALL OF MY CLASSES
import natural.selection.main.animalia.Animal;
import natural.selection.main.animalia.OurAnimal;
import natural.selection.main.animalia.Predator;
import natural.selection.main.animalia.Prey;
public class MainApp implements Runnable {
private Display display;
private int width, height;
public String title;
private boolean running = false;
private Thread thread;
private Random random = new Random();
private BufferStrategy bs;
private Graphics g;
private ArrayList<Animal> allAnimals = new ArrayList<>();
private int[] animalAmt = new int[20];
private ArrayList<Prey> allPreyAnimals = new ArrayList<>();
private int[] preyAnimalAmt = new int[20];
private ArrayList<OurAnimal> allOurAnimals = new ArrayList<>();
private int[] ourAnimalAmt = new int[20];
private ArrayList<Predator> allPredatorAnimals = new ArrayList<>();
private int[] predatorAnimalAmt = new int[20];
public MainApp(String title, int width, int height){
this.width = width;
this.height = height;
this.title = title;
}
private void init(){
display = new Display(title, width, height);
for(int i=0; i<90; i++) {
OurAnimal animal = new OurAnimal(random.nextInt(10), random.nextInt(10), random.nextInt(10), random.nextInt(10), random.nextInt(10), random.nextInt(10));
allOurAnimals.add(animal);
allAnimals.add(animal);
}
for(int i=0; i<(80+random.nextInt(10)); i++) {
Prey animal = new Prey(random.nextInt(10), random.nextInt(10), random.nextInt(10), random.nextInt(10), random.nextInt(10), random.nextInt(10));
allPreyAnimals.add(animal);
allAnimals.add(animal);
}
for(int i=0; i<(50+random.nextInt(10)); i++) {
Predator animal = new Predator(random.nextInt(10), random.nextInt(10), random.nextInt(10), random.nextInt(10), random.nextInt(10), random.nextInt(10));
allPredatorAnimals.add(animal);
allAnimals.add(animal);
}
animalAmt[0] = allAnimals.size();
preyAnimalAmt[0] = allPreyAnimals.size();
ourAnimalAmt[0] = allOurAnimals.size();
predatorAnimalAmt[0] = allPredatorAnimals.size();
}
private void tick() {
}
// Amount of weeks to simulate
private int weeksToSim = 20;
private void render(){
bs = display.getCanvas().getBufferStrategy();
if(bs == null){
display.getCanvas().createBufferStrategy(3);
return;
}
g = bs.getDrawGraphics();
//Clear Screen
g.clearRect(0, 0, width, height);
//Draw Here!
g.setColor(Color.black);
// LINE GRAPH OF SPECIES COUNT
// Draw the graph
for(int x=0; x<weeksToSim; x++) {
g.drawLine(x*93+125, height-100, x*93+125, 0);
g.drawString("Week " + (x+1), x*93+125-20, height-80);
}
for(int y=0; y<10; y++) {
g.drawLine((125), (y+1)*93, width, (y+1)*93);
g.drawString(Math.abs(y*10-90) + " alive", (80), (y+1)*93);
}
// Draw the line
for(int i=0; i<(animalAmt.length-1); i++) {
// predator animal line
g.setColor(Color.red);
g.drawLine(i*93+125, (Math.abs((predatorAnimalAmt[i]*10)-90)), (i+1)*93+125, (Math.abs((predatorAnimalAmt[i+1]*10)-90)));
g.drawLine(100, height-45, 120, height-45);
g.drawString("PREDATOR", 30, height-40);
// prey animal line
g.setColor(Color.green);
g.drawLine(i*93+125, (Math.abs((preyAnimalAmt[i]*10)-90)), (i+1)*93+125, (Math.abs((preyAnimalAmt[i+1]*10)-90)));
g.drawLine(100, height-60, 120, height-60);
g.drawString("PREY", 30, height-55);
// our animal's line
g.setColor(Color.blue);
g.drawLine(i*93+125, (Math.abs((ourAnimalAmt[i]*10)-90)), (i+1)*93+125, (Math.abs((ourAnimalAmt[i+1]*10)-90)));
g.drawLine(100, height-75, 120, height-75);
g.drawString("OUR ANIMAL", 30, height-70);
}
//End Drawing!
bs.show();
g.dispose();
}
public void run(){
init();
int fps = 60;
double timePerTick = 1000000000 / fps;
double delta = 0;
long now;
long lastTime = System.nanoTime();
long timer = 0;
int ticks = 0;
Toolkit.getDefaultToolkit().sync();
while(running){
now = System.nanoTime();
delta += (now - lastTime) / timePerTick;
timer += now - lastTime;
lastTime = now;
if(delta >= 1){
tick();
render();
ticks++;
delta--;
}
if(timer >= 1000000000){
System.out.println("Ticks and Frames: " + ticks);
ticks = 0;
timer = 0;
}
}
stop();
}
public int getWidth(){
return width;
}
public int getHeight(){
return height;
}
public synchronized void start(){
if(running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
public synchronized void stop(){
if(!running)
return;
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
How would I go about making all of the points correct with just one formula without completely disrupting all of my code?
Here is what I get as a result of my code:
Let's extract this functionality into two functions that calculate the correct x and y position for a given week and count. This way, you can change the chart layout by just changing a single function instead of multiple lines scattered throughout the code:
private int getChartX(double week) {
return (int)Math.round(week * 93 + 32);
}
private int getChartY(double count) {
return (int)Math.round(930 - count * 9.3);
}
Using these functions, you can re-structure your drawing code like this:
// Draw the graph
for(int week = 1; week <= weeksToSim; week++) {
int x = getChartX(week);
g.drawLine(x, getChartY(0), x, 0);
g.drawString("Week " + week, x-20, getChartY(0) + 20);
}
for(int y=0; y<10; y++) {
int count = 10 * y;
int y = getChartY(count);
g.drawLine(getChartX(1), y, width, y);
g.drawString(count + " alive", getChartX(1) - 45, y);
}
// Draw the line
for(int i=0; i<(animalAmt.length-1); i++) {
int week = i + 1;
// predator animal line
g.setColor(Color.red);
g.drawLine(getChartX(week), getChartY(predatorAnimalAmt[i]), getChartX(week + 1), getChartY(predatorAnimalAmt[i + 1]));
...
}
package harjutamine;
public class algandmed{
Button[] whitebutton= new Button[2];
Button[] blackbutton= new Button[2];
public algandmed(){
whitebutton[0] = new Button(5, 1);
whitebutton[1] = new Button(5, 3);
blackbutton[0] = new Button(0, 0);
blackbutton[1] = new Button(0, 2);
}
}
This is basic information for my main file.
I have tried algandmed(); and algandmed a = new algandmed(); to call the code in my main file which don't work and I don't know why, I'd be thankful if someone explained why those wouldn't work and what would work.
Main
package harjutamine;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Checkerboard extends JPanel implements ActionListener {
public void drawFrame(Graphics g, int frameNumber, int width, int height) {
int row; // Row number, from 0 to 7
int col; // Column number, from 0 to 7
int x, y; // Top-left corner of square
for (row = 0; row < 8; row++) {
//Kabelaud
for (col = 0; col < 8; col++) {
x = col * 50;
y = row * 50;
if ((row % 2) == (col % 2)) {
g.setColor(Color.BLACK);
} else {
g.setColor(Color.WHITE);
}
g.fillRect(x, y, 50, 50);
}
}
//This is where I try to call the function, but it doesn't work
algandmed aa = new algandmed();
for (Button n: (whitebutton)) {
x = n.col * 50 + 4;
y = n.row * 50 + 4;
g.setColor(Color.RED);
g.drawOval(x, y, 40, 40);
g.fillOval(x, y, 40, 40);
}
for (Button n: (blackbutton)) {
x = n.col * 50 + 4;
y = n.row * 50 + 4;
g.setColor(Color.BLUE);
g.drawOval(x, y, 40, 40);
g.fillOval(x, y, 40, 40);
}
}
//------ Implementation details: DO NOT EXPECT TO UNDERSTAND THIS ------
public static void main(String[] args) {
JFrame window = new JFrame("Checkerboard");
Checkerboard drawingArea = new Checkerboard();
drawingArea.setBackground(Color.WHITE);
window.setContentPane(drawingArea);
drawingArea.setPreferredSize(new Dimension(390, 390));
window.pack();
window.setLocation(100, 50);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false); // The user can't change the size.
Timer frameTimer = new Timer(20, drawingArea);
window.setVisible(true);
//frameTimer.start(); // commented out so we don't get an animation
} // end main
private int frameNum;
public void actionPerformed(ActionEvent evt) {
frameNum++;
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawFrame(g, frameNum, getWidth(), getHeight());
}
}
Button
package harjutamine;
public class Button{
int row;
int col;
public Button(int r, int c){
row = r;
col = c;
}
}
I guess what you are trying to say is that your code does not compile. There is no declaration for a Variable whitebutton in your drawFrame method. Therefor the compiler won't compile your code. If you simply paste the code algandmed then you have a declaration of whitebutton. However this is probably not what you wanted. Think about which class should hold/own the Button Arrays. If you decide to put them in the alganmed class you need to provide a correct variable declaration.aa.whitebutton should work because you created an instance of alganmed named aa. Since you are in the same package and whitebutton is default visibility you can access it directly from your main method. Note however that this is not good practice. You should not access another classes internal data directly. Try to think of methods that encapsulate the data of alganmed instead.
I have been looking at this one for a while and it doesn't make sense. When I start my program, I set the background color of a grid of rectangles to a specific color using the SetupLawn call from my main function in a different file. That part works fine. Then when I try to change the color later by calling the SetupLawn function again with a new color it doesn't change. I put prints in the SetupLawn function and the color I am passing is getting there correctly but as soon as paintComponent gets called the value of currentColor is back to being what it was originally. I verified this with a debug print as well.
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class Lawn
{
public static class SetupLawn extends JPanel
{
private List<Point> lawn;
Color currentColor;
public SetupLawn(Color color)
{
lawn = new ArrayList<>(25);
currentColor = color;
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
for (Point cell : lawn)
{
int cellX = cell.x;
int cellY = cell.y;
g.setColor(currentColor);
g.fillRect(cellX, cellY, 50, 50);
}
//Set grid color and draw border
g.setColor(Color.BLACK);
g.drawRect(10, 10, 800, 500);
for (int i = 10; i <= 800; i += 50)
{
g.drawLine(i, 10, i, 510);
}
for (int i = 10; i <= 500; i += 50)
{
g.drawLine(10, i, 810, i);
}
for (int i = 60; i <= 750; i += 50)
{
for (int j =60; j <= 450; j += 50)
{
lawn.add(new Point(i, j));
}
}
}
}
}
Here is the way I was calling it.
Lawn.SetupLawn lawn = new Lawn.SetupLawn(spring);
I can see now why this method was not a good idea. It was really late at night when I was working on this and Java is not a strong language for me.
I created a simple "elevator" program (it's still in the beginning stages) that goes up 1 floor when I click UP and vice versa.
I messed up pretty badly when I drew all my components into JFrame, and as expected, it flickers every time I click the button (repaints). I know the solution to be draw in the JPanel and put the said panel in the JFrame, but I have a problem translating my JFrame components into JPanel. I've tried extending JPanel, creating a JFrame object and then overriding the paintComponent() method and doing my drawing there, but when I compile it does not draw it at all. It only creates the frame.
Can anyone help me or give me tips on how to proceed "transferring" my programming from JFrame based to JPanel based? Thank you in advance!
My code is below:
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.Timer;
import java.math.*;
public class MyCanvas extends JFrame {
private int up = 0;
private int down = 0;
private int movefloorup = 0;
private int buildingType;//type of building (1 = Residential, 2 = Commercial)
private int totnumoffloors; //for the total number of floors
private int numofelevators; //for the number of elevators to be generated
private int floorlimit = 0; //to determine up until where the elevator will be moving
private int currenttime; //determine the time of the day the elevator is operating (1 = Morning, 2 = Lunch, 3 = Afternooon)
//For elevator resetting to bottom
private int rectX = 190;
private int switchmarker = 0;
//Lines and stuff
private int horizborder = 0;
private int bordercount = 0;
private class UpAction implements ActionListener //move the elevator up
{
public void actionPerformed(ActionEvent e)
{
if(movefloorup<780){
repaint();
up++;
movefloorup = movefloorup + 130;
//repaint();
}
else
{
switchmarker = 1;
movefloorup = 0;
repaint();
}
}
}
private class DownAction implements ActionListener //move the elevator down
{
public void actionPerformed(ActionEvent e)
{
if(movefloorup>0){
repaint();
down++;
movefloorup = movefloorup - 130;
//repaint();
}
else
{
switchmarker = 0;
movefloorup = 780;
repaint();
}
}
}
public MyCanvas(int buildingType, int totnumoffloors, int numofelevators, int currenttime){
this.buildingType = buildingType;
this.totnumoffloors = totnumoffloors;
this.numofelevators = numofelevators;
this.currenttime = currenttime;
String title;
if(this.buildingType == 1)
{
title = "Residential Building";
}
else
{
title = "Commercial Building";
}
setLayout(null);
horizborder = 500*((int)Math.ceil((double)totnumoffloors/7)); //calculating how wide the window should be
bordercount = ((int)Math.ceil((double)totnumoffloors/7)); //counts how many borders there will be
//NOTES
//A floor is 130 units in the Y-Direction
//Drawing the bulding layout
if(totnumoffloors>7)
{
setSize(horizborder, 1000);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(title);
setLayout(new BorderLayout());
getContentPane().setBackground(Color.WHITE);
}
else{
setSize(500, 1000); //suitable for 7 floors
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(title);
setLayout(new BorderLayout());
getContentPane().setBackground(Color.WHITE);
}
JButton upButton = new JButton("UP");
upButton.addActionListener(new UpAction());
add(upButton, BorderLayout.NORTH);
JButton downButton = new JButton("DOWN");
//downButton.setBounds(0, 0, 220, 30);
//downButton.setLocation(100, 100);
downButton.addActionListener(new DownAction());
add(downButton, BorderLayout.SOUTH);
}
public void paint(Graphics graphics){ //this is where you draw shit
super.paint(graphics);
//Floors
graphics.setColor(Color.RED);
int numoffloorsY = 830;
int numoffloorsX = 830;
int floorbeginning = 0;
int floorcounter = 1;
int floorflag = 0;
int rightedge = 500;
if(this.totnumoffloors>7) //drawing the floors
{
//Default number of floors -> 7
for(int i = 0;i<totnumoffloors;i++)
{
graphics.setColor(Color.RED);
graphics.drawLine(floorbeginning,numoffloorsX,rightedge,numoffloorsY); //FLOORS
graphics.setColor(Color.DARK_GRAY);
graphics.setFont(new Font("TimesRoman", Font.PLAIN, 15));
graphics.drawString(" "+floorcounter, floorbeginning+10, numoffloorsY+20); //SAVE THIS FOR DRAWING FLOORS
numoffloorsY = numoffloorsY - 130;
numoffloorsX = numoffloorsX - 130;
floorcounter++;
floorflag++;
if(floorflag==7)
{
floorbeginning = floorbeginning + 500;
rightedge = rightedge+500;
numoffloorsY = 830;
numoffloorsX = 830;
floorflag = 0;
}
}
//Every other floor past 7 will be added here.
/*for(int i = 0;i<totnumoffloors-7;i++)
{
//System.out.println("LOLOOLO");
graphics.setColor(Color.RED);
graphics.drawLine(floorbeginning,numoffloorsX,horizborder,numoffloorsY);
graphics.setColor(Color.DARK_GRAY);
graphics.setFont(new Font("TimesRoman", Font.PLAIN, 15));
graphics.drawString(" "+floorcounter, floorbeginning, numoffloorsY+20);
//graphics.setColor(Color.DARK_GRAY);
//graphics.drawLine(500,0,500,1000);
floorcounter++;
numoffloorsY = numoffloorsY - 130;
numoffloorsX = numoffloorsX - 130;
}*/
//DIVIDING LINE -> to determine the first 7 floors from the ones higher up.
for(int i=0;i<bordercount;i++)
{
graphics.setColor(Color.DARK_GRAY);
graphics.drawLine(500*i,0,500*i,1000);
}
}
else{
for(int i = 0;i<this.totnumoffloors;i++)
{
graphics.setColor(Color.RED);
graphics.drawLine(0,numoffloorsX,500,numoffloorsY);
graphics.setColor(Color.DARK_GRAY);
graphics.setFont(new Font("TimesRoman", Font.PLAIN, 15));
graphics.drawString(" "+floorcounter, floorbeginning+10, numoffloorsY+20); //SAVE THIS FOR DRAWING FLOOR
numoffloorsY = numoffloorsY - 130;
numoffloorsX = numoffloorsX - 130;
floorcounter++;
}
}
//Drawing the elevators
if(up>0 && movefloorup<1000){
graphics.setColor(Color.GRAY);
if(switchmarker==1)
{
System.out.println("ELSA");
rectX = 690;
//rectX = rectX + 190;
}
else
{
rectX = 190;
}
System.out.println(rectX);
graphics.fillRect(rectX, 850-movefloorup, 100, 100); //this needs to match the stats of the rectangle to fill it properly
graphics.drawRect(rectX, 850-movefloorup, 100, 100);
//Line for the door
graphics.setColor(Color.BLACK);
graphics.drawLine(rectX+50, 850-movefloorup, rectX+50, 950-movefloorup); //match the y-coordinate for the rectangle, add 100 for the y-coordinate of the other end
System.out.println(movefloorup);
System.out.println(switchmarker);
//drawLine(x1, y1, x2, y2); --From (x1,y1) to (x2,y2)
}
else if(down>0 && movefloorup>0)
{
graphics.setColor(Color.GRAY);
if(switchmarker==1) //This determines when the elevator should move to the next column of higher floors.
{
System.out.println("ELSA");
rectX = 500;
}
System.out.println(rectX);
graphics.fillRect(rectX, 850-movefloorup, 100, 100); //this needs to match the stats of the rectangle to fill it properly
//graphics.drawRect(190, 850 + movefloorup, 100, 100); //FIRST FLOOR
graphics.drawRect(rectX, 850-movefloorup, 100, 100); //SECOND FLOOR (135 units difference in Y-axis between floors)
//x-coordinate, y-coordinate, width, height
//Line for the door
graphics.setColor(Color.BLACK);
graphics.drawLine(rectX+50, 850-movefloorup, rectX+50, 950-movefloorup); //match the y-coordinate for the rectangle, add 100 for the y-coordinate of the other end
System.out.println(movefloorup);
System.out.println(switchmarker);
}
else
{
graphics.setColor(Color.GRAY);
graphics.fillRect(190, 850, 100, 100); //this needs to match the stats of the rectangle to fill it properly
graphics.drawRect(190, 850, 100, 100); //FIRST FLOOR
graphics.drawRect(190, 850, 100, 100); //SECOND FLOOR (135 units difference in Y-axis between floors)
//x-coordinate, y-coordinate, width, height
//Line for the door
graphics.setColor(Color.BLACK);
graphics.drawLine(240, 850, 240, 950); //match the y-coordinate for the rectangle, add 100 for the y-coordinate of the other end
//System.out.println("In else!");
}
}
}
The main class just gets input from the user, such as the number of floors, time of day, etc.
This is going to be a little messy.
Start by creating a custom component that extends from JPanel (I'll call it ElevatorPane).
Take the contents of the current paint method and place them within this components paintComponent method. This will involve moving the instance variables that the paintComponent method will need including, totnumoffloors, bordercount, up, down, movefloorup, switchmarker, rectX
This is where it gets a little messy...
You need to take the contents of your ActionListeners and translate these into methods within the ElevatorPane, this way you expose the functionality without exposing the details...
Create a constructor within ElevatorPane that takes the number of floors.
Override the getPrefferedSize method of ElevatorPane and return the size that the component needs to be to satisfy your needs...
Create an instance field of ElevatorPane in MyCanvas, instantiate it and add it to the frame.
Clean, build, run...