【问题标题】:How can I write the name of an image and its coordinates into a save.txt file?如何将图像的名称及其坐标写入 save.txt 文件?
【发布时间】:2015-10-18 11:09:57
【问题描述】:

我将如何编写“如果将贴纸 1 放置在数组中”然后...我的目标是放置贴纸并将其作为带有坐标的名称输入到数组中,然后保存到 save.txt 文件中。从那里,我可以单击加载按钮,它会加载贴纸并将其放置在确切的坐标处。

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

然后是保存代码。

else if (savePicture.isPointInElement(clickX, clickY)){
FileWriter fw = new FileWriter("save.txt");
for (int i = 0; i < arraysticker.length; i++);
    if (sticker1.images[images].isShowing){
    //I want the iff statement ^^ to say if sticker if placed in the array
    //fw.write name and coords into save.txt    
    }
}

【问题讨论】:

    标签: java arrays save


    【解决方案1】:

    你应该有类Stricker,它应该看起来像这样:

    public class Sticker(){
      private String name;
      private int X;
      private int Y;
    
      //There You should place Getters and Setters to variables name,X and Y
      //... and your method named 'arraysticker(Object, Image, Integer, Integer)'
    }
    

    ...下一步是创建正确类型的列表ArrayList&lt;Sticker&gt; list = new ArrayList&lt;&gt;();

    我会这样做:

    if(hatSoundPlay){ 
       hatsound.play(); 
       Sticker sticker1 = new Sticker();
    
       sticker1.arraysticker(hatPicture, "hat.png", clickX, clickY);
    
       image ++;
       list[image] = sticker1;
    }
    

    最后你的保存代码应该是这样的:

    else if (savePicture.isPointInElement(clickX, clickY)){
       FileWriter fw = new FileWriter("save.txt");
       for(int i = 0; i < list.length; i++){
           if(list[i]!=null){ //if object exist, do...
             String name;
             int x,y;
    
             name = list.getName();
             x = list.getX();
             y = list.getY();
    
             fw.write(name + " " + x + " " + y + "\n"); //write all elements to file separated with space and symbol of new line
           }
        }
      fw.close(); //necessary to close connection with file
    }
    

    为了解决这个问题,我需要剩下的代码,因为我没有关于 Yours 方法和其他数组的信息,例如 images

    【讨论】:

      【解决方案2】:

      就您需要保存和恢复对象而言,我建议您使用一些现成的解决方案,例如 Jackson 库。这简化了逻辑,您只需使用注释即可控制要保存和恢复的内容。

      有很多例子。所以你得到你的类,用注释标记属性,就是这样。 Jackson lib 将为您做一切。看看这个教程:http://www.journaldev.com/2324/jackson-json-processing-api-in-java-example-tutorial

      【讨论】:

        猜你喜欢
        • 2016-01-16
        • 1970-01-01
        • 2023-03-27
        • 2016-05-11
        • 2020-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多