2015-10-19 2 views
1

Мне нужно создать четкую кнопку, которая при нажатии удаляет все изображения с экрана. Изображения в настоящее время находятся в массиве. Я только что сохранил то, что было в массиве, в файле save.txt. Теперь мне нужно нажать на загрузку, которая удаляет все изображение с экрана перед загрузкой там, где они были раньше. Как мне это сделать? Это мой сохранить кодКак я могу очистить весь массив?

else if (savePicture.isPointInElement(clickX, clickY)){ 
    FileWriter fw = new FileWriter("save.txt"); 
    for (int i = 0; i < image; i++){ 

     if (arraysticker[image] != null){ 
      String name; 
      int x,y; 
      name = sticker.getname(); 
      x = sticker.getx(); 
      y = sticker.gety(); 
      fw.write(name + " " + x + " " + y + "\n"); 
     } 
    } 
    fw.flush(); 
    fw.close(); 
    System.out.println("saved"); 
} 

Весь мой код

public class main { 
public static void main(String[] args) throws IOException { 
    EZ.initialize(1644,1022);//sets page size 
    sticker [] arraysticker = new sticker [20];//creates an array to hold 20 sticker 
    EZImage backgroundPicture = EZ.addImage("background.png", EZ.getWindowWidth()/2, EZ.getWindowHeight()/2); //set position of background 
    EZImage rectanglePicture = EZ.addImage("rectangle.png", EZ.getWindowWidth()/2, EZ.getWindowHeight()/7); //set position of palette 
    EZImage hatPicture = EZ.addImage("hat.png",1* EZ.getWindowWidth()/10, EZ.getWindowHeight()/6); //set position of stickers 
    EZImage bluntPicture = EZ.addImage("blunt.png",1* EZ.getWindowWidth()/3, EZ.getWindowHeight()/6); //set position of stickers 
    EZImage dealwithitPicture = EZ.addImage("dealwithit.png",3* EZ.getWindowWidth()/5, EZ.getWindowHeight()/6); //set position of stickers 
    EZImage weedPicture = EZ.addImage("weed.png",10* EZ.getWindowWidth()/11, EZ.getWindowHeight()/6); //set position of stickers 
    EZImage savePicture = EZ.addImage("save.png", 19* EZ.getWindowWidth()/20, 3* EZ.getWindowHeight()/9); //set position of save button 
    EZImage loadPicture = EZ.addImage("load.png", 19* EZ.getWindowWidth()/20, 4* EZ.getWindowHeight()/9); 
    EZImage clearPicture = EZ.addImage("clear.png", 19* EZ.getWindowWidth()/20, 5* EZ.getWindowHeight()/9); 

    EZSound hatsound = EZ.addSound("airhorn.wav"); //imports airhorn.wav and assigns it to hatsound 
    EZSound bluntsound = EZ.addSound("yungdog.wav"); //import yungdog.wav and assigns it to bluntsound 
    EZSound dealwithitsound = EZ.addSound("sandstorm.wav"); //imports sandstorm.wav and assigns it to dealwithitsound 
    EZSound weedsound = EZ.addSound("weed.wav"); //imports weed.wav and assigns it to weedsound 

    sticker arrayhat = new sticker (20, "hat.png"); 
    sticker arrayblunt = new sticker (20, "blunt.png"); 
    sticker arraydealwithit = new sticker (20, "dealwithit.png"); 
    sticker arrayweed = new sticker (20, "weed.png"); 

    int image = 0;//declares an integer variable named image 
    //creates a boolean variable and sets it to false 
    boolean hatSoundPlay = false; 
    boolean bluntSoundPlay = false; 
    boolean dealwithitSoundPlay = false; 
    boolean weedSoundPlay = false; 
     while (true){//while it is true 
     if (EZInteraction.wasMouseLeftButtonReleased()){//if left button is released 
     int clickX = EZInteraction.getXMouse(); //get x coordinates 
     int clickY = EZInteraction.getYMouse();//get y coordinates 

      if (hatPicture.isPointInElement(clickX, clickY)){//if hat is in the x and y coordinates 
       bluntSoundPlay = false; //turn all sounds false 
       weedSoundPlay = false; 
       dealwithitSoundPlay = false; 
       if (!hatSoundPlay) { //if hatsound not play 
        hatsound.play(); //hatsound will play 
        hatSoundPlay = true; //hat sound is now true  
       } 
      } 
      else if(bluntPicture.isPointInElement(clickX, clickY)){//if blunt is in the x and y coordinates 
       hatSoundPlay = false;//turn all sounds false 
       weedSoundPlay = false; 
       dealwithitSoundPlay = false; 
       if (!bluntSoundPlay) {//if bluntsound not play 
        bluntsound.play(); //then bluntsound will play 
        bluntSoundPlay = true; //bluntSoundPLay is now assigned to true 
       } 
      } 
      else if(dealwithitPicture.isPointInElement(clickX, clickY)){//if dealwithit is in the x and y coordinates 
       hatSoundPlay = false;//turn all sounds false 
       bluntSoundPlay = false; 
       weedSoundPlay = false; 
       if (!dealwithitSoundPlay) {//if dealwithitsound not play 
        dealwithitsound.play(); //then dealwithitsound will pay 
        dealwithitSoundPlay = true; //dealwithitSoundPlay is assigned as true 
       } 
      } 
      else if(weedPicture.isPointInElement(clickX, clickY)){//if weed is in the x and y coordinates 
       dealwithitSoundPlay = false;//turn all sounds false 
       hatSoundPlay = false; 
       bluntSoundPlay = false; 
       if (!weedSoundPlay) {//if weedsound not play 
        weedsound.play(); //then weedsound will play 
        weedSoundPlay = true; //sets the varialbe weedSoundPlay to true 
       } 
      } 


      else if (backgroundPicture.isPointInElement(clickX, clickY) && !savePicture.isPointInElement(clickX, clickY) 
        && !loadPicture.isPointInElement(clickX, clickY) && !clearPicture.isPointInElement(clickX, clickY) 
        && !rectanglePicture.isPointInElement(clickX, clickY)){ 
       if (hatSoundPlay){ //if hatSoundPlay is true 
        hatsound.play(); //and a hatsound will play 
        sticker sticker1 = new sticker();//creates a new sticker1 
        sticker1.arraysticker(hatPicture, "hat.png", clickX, clickY);//places sticker 
        image ++;//increments image by 1 
        arraysticker[image] = sticker1;//puts sticker 1 into the array 
        FileWriter fw = new FileWriter("save.txt"); 


       } else if (bluntSoundPlay){ //else if bluntSound is true 
        bluntsound.play(); //and blunt sound will play 
        sticker sticker2 = new sticker(); 
        sticker2.arraysticker(bluntPicture, "blunt.png", clickX, clickY);//places sticker 
        image ++;//increments image by 1 
        arraysticker[image] = sticker2;//puts sticker 2 into the array 

       }else if (dealwithitSoundPlay){ //if dealwithitsound is true 
        dealwithitsound.play(); //dealwithitsound will play 
        sticker sticker3 = new sticker(); 
        sticker3.arraysticker(dealwithitPicture, "dealwithit.png", clickX, clickY);//places sticker 
        image ++;//increments image by 1 
        arraysticker[image] = sticker3;//puts sticker 3 into the array 

       }else if (weedSoundPlay){ //if weedsound is true 
        weedsound.play(); //weedsound will also play 
        sticker sticker4 = new sticker(); 
        sticker4.arraysticker(weedPicture, "weed.png", clickX, clickY);//places sticker 
        image ++;//increments image by 1 
        arraysticker[image] = sticker4;//puts sticker 4 into the array 
       } 
      } 
      else if (savePicture.isPointInElement(clickX, clickY)){ 
       FileWriter fw = new FileWriter("save.txt"); 
       for (int i = 0; i < image; i++){ 

        if (arraysticker[image] != null){ 
         String name; 
         int x,y; 
         name = sticker.getname(); 
         x = sticker.getx(); 
         y = sticker.gety(); 
         fw.write(name + " " + x + " " + y + "\n"); 
        } 
       } 

       fw.flush(); 
       fw.close(); 
       System.out.println("saved"); 
      } 
      /*else if (loadPicture.isPointInElement(clickX, clickY)){ 
       Scanner sc = new Scanner (new File ("save.txt")); 
       for (int i = 0; i < image; i++){ 
        arraysticker.removeImage(arraysticker.image1[image]); 
       } 
      }*/ 

    } 
     EZ.refreshScreen();  
    } 
} 

}

+1

может 'arraysticker = новый стикер [arraysticker.length];' быть достаточно? – SomeJavaGuy

ответ

0

Просто назначьте null в качестве ссылки.

arraysticker = null; // garbage collector will take care 

или

arraysticker = new sicker[arraysticker.length]; // initialized to new length 

или использовать

Arrays.fill(arraysticker, null);

это просто перебирает каждый элемент и устанавливает его в нулевое значение. Это из курс не позволяет изменять размер массива (до нуля), если это то, что вы имели в виду под «пустым».

public static void fill(Object[] a,Object val) 

Назначает указанное ссылку на объект каждого элемента указанного массива объектов.

Параметры: а - массив, который будет заполнен Val - значение, которое хранится во всех элементах массива Броски: ArrayStoreException - если указанное значение не типа времени выполнения, который может быть сохранен в указанном массив

1

Если arraysticker не является окончательным, то простым переназначение будет работать:

arraysticker = new sicker[arraysticker.length]; 

Это предполагает, что вам нужно массив оставаться таким же размером. Если это не нужно, то создать пустой массив:

arraysticker = new sicker[0]; 

Если это является окончательным, то вы можете обнулить все элементы:

Arrays.fill(arraysticker, null); 
+0

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

Смежные вопросы