2015-03-11 3 views
0

У меня есть проект домашней работы, над которым я серьезно застрял. Или в значительной степени только одна часть его и нужна помощь в выяснении. Я в основном использую java для создания зданий с произвольным размером, и внутри этих зданий я создам случайные окна. До сих пор у меня были случайные здания, но у меня появилось только одно окно для каждого здания. когда я пытаюсь вставить цикл for, он перемещает мои окна в конец экрана. Я чувствую, что проблема заключается в координатах x и нужно как-то сбросить ее. Любая помощь будет оценена. Программа состоит из трех частей: класс здания, панель и основной. Это мой второй семестр программирования, поэтому я действительно довольно новый.inested for loop java

PS. Я уже включил его и получил кредит, но я все еще очень хочу знать, как сделать эту часть программы.

/**Written by Paul Ancajima 
* last updated 2/25/15 
* RandomSkyline panel 
* this is where i bring over Building and have them draw itself 
*/ 
import javax.swing.*; 
import java.awt.*; 

public class SkylinePanel extends JPanel{ 

    //initialize variables 
    private int x=5+(int)(Math.random()*((10-5))+1); 
    private int w; 
    private int l=120+(int)(Math.random()*((300-120)+1)); 
    private int x1; 
    private int y1=150+(int)(Math.random()*((170-150))+1); 
    private int gap = 2+(int)(Math.random()*5-2); 
    //first windowX and windowY start at 0,0 
    private int windowX=5+(int)(Math.random()*((15-5))+1); 
    private int windowY = (y1)+(int)(Math.random()*((130-y1))+1); 
    private int starX=25+(int)(Math.random()*((50-25))+1); 
    private int roadX; 
    private int roadX2=10; 
    //random number of windows 
    private int winNum = (int)(Math.random()*5*x); 
    //arrays or buildings, windows,and stars; 
          //figure out how to use winNum 
    private Building[]windowArr= new Building[x]; 
    private Star[]starArr = new Star[starX]; 
    private Building[]buildingArr = new Building[x]; 

    public SkylinePanel(){ 

     //loop to create all the buildings 
     for(int y=0; y<buildingArr.length; y++){ 

      buildingArr[y] = new Building(x1, y1, w, l, x, Color.blue); 
      x1=w+gap+x1; 
      y1=(int)(Math.random()*20)+120; 
      w=20+(int)+(Math.random()*((35-20))+1); 
      l=(int)(Math.random()*300)+80; 
      gap = 2+(int)(Math.random()*5-2); 

      //FIX THE LOOP 
      //for(int zz=0; zz<buildingArr.length; zz++){ 
      windowArr[y]= new Building(windowX,windowY, 3, 3, x, Color.yellow); 
      windowX = x1+(int)(Math.random()*(((x1+(w-gap))-x1))+1); 
      windowY = 160+(int)(Math.random()*((y1-(160)))+1); 
      // } 

      for(int zz=0; zz<starArr.length; zz++){ 
       starArr[zz]= new Star((int)(Math.random()*x1), 0+(int)(Math.random()*((100+0))+1), 1, 1,Color.yellow); 
      } 

      //the Dimension of the screen will be the size of width of all buildings plus all gaps = x1+w+gap 
      setPreferredSize (new Dimension(x1, 200)); 
      setBackground (Color.black); 
     } 

    } 

    public void paintComponent (Graphics page){ 

     super.paintComponent(page); 
     page.setColor(Color.black); 

     for(int i = 0; i<starArr.length;i++){ 
      starArr[i].draw(page); 
     } 

     //loop to draw all the buildings 
     for(int i=0; i<buildingArr.length; i++){ 
      buildingArr[i].draw(page); 
     } 

     //loop to draw all windows(needs work/ change to windowsArr.length) 
     for(int i=0; i<buildingArr.length; i++){ 
      windowArr[i].draw(page); 
     } 

     page.setColor(Color.white); 
     page.fillOval(x1-35, 30, 30, 30); 
     page.setColor(Color.gray); 
     page.fillRect(0, 180, x1, 20); 
     page.setColor(Color.yellow); 

     for(int j=0; j<180; j++){ 
      page.drawLine(roadX, 190, roadX2, 190); 
      roadX=roadX+20; 
      roadX2=roadX2+20; 
     } 
    } 
} 








/**Written by Paul Ancajima 
* Building class 
* last updated 2/25/15 
*/ 

import java.awt.*; 

public class Building{ 

    private int x,y, width, height,window; private Color color; 

    public Building(int x1, int y1, int w, int h, int window, Color shade){ 

     x= x1; 
     y=y1; 
     width =w; 
     height = h; 
     color = shade; 
    } 

    public int setX(int x1){ 

     return x1; 
    } 

    public int setY(int y1){ 

     return y1; 

    } 

    public int getWidth(int w){ 

     return w; 
    } 

    public int getHeight(int h){ 

     return h; 
    } 

    public void draw(Graphics page){ 

     page.setColor(color); 
     page.fillRect(x, y, width, height); 

    } 

    public void getWindows(int x,int y,int w,int h,Color shade){ 

     this.x=x; 
     this.y=y; 
     width=w; 
     height=h; 
     color=shade; 
    } 
} 

/**written by Paul Ancajima 
* Skyline main 
* last updated 2/25/15 
*/ 

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

public class RandomSkyline{ 

    public static void main (String[] args){ 

     JFrame frame = new JFrame ("Paul's city"); 
     frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(new SkylinePanel()); 
     frame.pack(); 
     frame.setVisible(true); 

    } 

} 
+0

У вас есть оконный массив, который имеет тип здания? смотрит на меня, что ваш дизайн плох. Разве «Строение» не должно содержать коллекцию «Windows», которая может быть размещена на основе позиции здания? – John3136

+0

это было бы потрясающе, но я не уверен, как это сделать. –

ответ

0

Ваш Building класс должен содержать массив Windows, если вы хотите больше, чем одно окно на здание. т.е.

public class Building{ 

    private int x,y, width, height,window; private Color color; 
    private Window[] windows = new Window[]; // This could also be done with a collection rather than an array, they are easier to work with if you are adding and removing. 

    public Building(int x1, int y1, int w, int h, int window, Color shade){ 

     x= x1; 
     y=y1; 
     width =w; 
     height = h; 
     color = shade; 
    } 

... 

    // Change getWindows to the following 
    public Window[] getWindows(){ 
     return windows; 
    } 

    // add a method to generate the windows for the building. 
    public void createWindows(int numWindows) { 
     // initialise Window array based on parameter 
     windows = new Window[numWindows]; 

     // loop through for the length of the array 
     for (int i = 0; i < windows.size; i++) { 
      windows[i] = new Window(); // insert whatever parameters you want for the window. You probably need to check they stay inside the bounds of the building at least. 
     } 
    } 
+0

Спасибо, что работаю над этим прямо сейчас. похоже, что я должен предоставить измерение или число в окне [] windows = new Window []. –

+0

часть, где окна [i] = new Window(); говорит, что конструктор Window() не виден не уверен, что это значит –

+0

убедитесь, что в вашем классе Window конструктор Window() определяется как public -> public Window() {..} – Subler