Write in File XML

Hello everyone,

I am researching how to service XML file, so far managed to read a file generated, but I'm having trouble adding a record in an existing file, and also delete a specific item.

I'm looking for example ( addChild() ):

https://processing.org/reference/XML_addChild_.html

[code below]

As it would be to add another item? For example: Lions

One more thing, as I would to delete a specific item?

For example, to remove: Zebra

I hope you understood any help, I thank you.

Answers

  • Sorry, no marked the text code ...

    // The following short XML file called "mammals.xml" is parsed 
    // in the code below. It must be in the project's "data" folder.
    //
    // <?xml version="1.0"?>
    // <mammals>
    //   <animal id="0" species="Capra hircus">Goat</animal>
    //   <animal id="1" species="Panthera pardus">Leopard</animal>
    //   <animal id="2" species="Equus zebra">Zebra</animal>
    // </mammals>
    
    XML xml;
    
    void setup() {
      xml = loadXML("mammals.xml");
      XML newChild = xml.addChild("animal");
      newChild.setContent("bloodhound");
      println(xml);
    }
    
    // Sketch prints:
    // <mammals>
    //   <animal id="0" species="Capra hircus">Goat</animal>
    //   <animal id="1" species="Panthera pardus">Leopard</animal>
    //   <animal id="2" species="Equus zebra">Zebra</animal>
    // <animal>bloodhound</animal>
    // </mammals>
    
  • here is the idea

    problem is, you need to find the highest id and then go on from here to write new ids....

    ;-)

    // The following short XML file called "mammals.xml" is parsed 
    // in the code below. It must be in the project's "data" folder.
    //
    
    XML xml;
    
    void setup() {
      size(600, 600);
      text("Hit s to overwrite / save.", 30, 30);
      xml = loadXML("mammals.xml");
      println(xml+"\n--------------------\n");
    
    
      XML newChild = xml.addChild("animal");
      newChild.setContent("bloodhound");
      newChild.setString("species", "Jamides bloodhound");
      newChild.setInt("id", 5);
    
      newChild = xml.addChild("animal");
      newChild.setContent("Lion");
      newChild.setString("species", "Jamides Lion");
      newChild.setInt("id", 6);
    
      println(xml);
    }
    
    void draw() {
      //
    }
    
    void keyPressed() {
      if (key=='s') {
        saveXML(xml, dataPath("")+"/mammals.xml");
        println("Saved.");
      }
    }
    
  • you can write a function for the animal

    // The following short XML file called "mammals.xml" is parsed 
    // in the code below. It must be in the project's "data" folder.
    //
    
    XML xml;
    
    void setup() {
      size(600, 600);
      text("Hit s to overwrite / save.", 30, 30);
      xml = loadXML("mammals.xml");
      println(xml+"\n--------------------\n");
    
      addChild("animal", 5, "Jamides bloodhound", "bloodhound");
      addChild("animal", 6, "Jamides Lion", "Lion");
    
      println(xml);
    }
    
    void draw() {
      // empty
    }
    
    // --------------------------------------------------------------
    // Inputs and Tools 
    
    void keyPressed() {
      if (key=='s') {
        saveXML(xml, dataPath("")+"/mammals.xml");
        println("Saved. *************************************");
      }
    }
    
    void addChild( String branch, int id, String speciesName, String animalName ) {
    
      XML newChild = xml.addChild(branch);
    
      newChild.setContent(animalName);
      newChild.setString("species", speciesName);
      newChild.setInt("id", id);
    }
    //
    
  • Hello,

    Thanks for return now "cleared" how can I do, I will adapt as my need ...

    Thank you very very much,

    att,******** :)

  • Hello, Chrisir,

    At times you will need to remove a specific item, how could I do that?

    For example, removing item:

    <animal id="1" species="Panthera pardus">Leopard</animal>

    Example on the site explains how to remove first on the list, not a specific one.

    // The following short XML file called "mammals.xml" is parsed 
    // in the code below. It must be in the project's "data" folder.
    //
    // <?xml version="1.0"?>
    // <mammals>
    //   <animal id="0" species="Capra hircus">Goat</animal>
    //   <animal id="1" species="Panthera pardus">Leopard</animal>
    //   <animal id="2" species="Equus zebra">Zebra</animal>
    // </mammals>
    
    XML xml;
    
    void setup() {
      xml = loadXML("mammals.xml");
      XML firstChild = xml.getChild("animal");
      xml.removeChild(firstChild);
      println(xml);
    }
    
    // Sketch prints:
    // <mammals>
    //   
    //   <animal id="1" species="Panthera pardus">Leopard</animal>
    //   <animal id="2" species="Equus zebra">Zebra</animal>
    // </mammals>
    

    Many thanks again

  • // The following short XML text is parsed 
    // in the code below. 
    //
    
    XML xml;
    
    void setup() {
      size(233, 333);
    
    
      String[] data = {  
        "<mammals>", 
        "<animal id=\"0\" species=\"Capra hircus\">Goat</animal>", 
        "<animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>", 
        "<animal id=\"2\" species=\"Equus zebra\">Zebra</animal>", 
        "</mammals>"
      };
    
      //xml = loadXML("mammals.xml");
      xml = parseXML(join(data, "\n"));
    
      XML firstChild = xml.getChild("animal/\"2\"");
      // XML animalChild = firstChild.getChild("Zebra");
      // println(firstChild.getContent());
    
      showAll(); 
    
      killXML("Zebra"); 
    
      showAll();
    }
    
    void draw() {
      //
    }
    
    void killXML(String strKillWhat) {
    
      XML[] animals1 = xml.getChildren("animal");
    
      for (int i = 0; i < animals1.length; i++) {
        //  println(animals1[i].getContent());
        if (animals1[i].getContent().equals(strKillWhat)) {
          xml.removeChild(animals1[i]);
          return; // leave
        }// if
      }
    } //func 
    
    void showAll() {
      XML[] animals = xml.getChildren("animal");
    
      println("----------------------------");
    
      for (int i = 0; i < animals.length; i++) {
        println(animals[i].getContent());
      }
    }
    //
    
  • Answer ✓

    I managed only with a for-loop

    should be possible with a xml.getChildren("animal"); or

    xml.getChildren("animal/Zebra");

    but didn't work

  • OK,

    but asssim is very good, I can solve the problem ... thanks a lot, and thanks! :)

  • Hello again,

    I have a "little big" problem to complete part of the project, I will try to explain.

    The Project "set up" the menu to videos for each patient, ie a therapist can add options for videos (favorites) for each patient, so that it can use more easily through some device like the Kinect and the Leap Motion as they are for guests with limited mobility ...

    Obs .: clipped the photo image of the patient, to preserve the identity ...

    My problem is as follows:

    When you remove the link (button image), associated with an XML file, update all OK, that is, exclude the image and update the XML file in this case I would only need to make the button clicked stay invisible or could remove even the animation.

    The problem is dynamically set up, ie the number of images may vary, as already adicionao for each patient.

    You have a discussion on this link, passing an idea about it, but in this case is only one button:

    Link: http://forum.processing.org/one/topic/controlp5-show-and-hide.html

    In my case I had a "list" buttons, would have to have a means of identifying which really I clicked.

    I thought to create the objects in the form of Array (in this case I'm using the Controlp5 library), and thus control each according to delete.

    I hope you had understand, any hint, I thank you.

    Code Project: ( Only remove Item )

    public static final class RemoveItem extends PApplet {
      private ControlP5 cp5_01; //Cria objeto da biblioteca ControlP5
    
      XML xml_01, xml_02; //Variável para carregar arquivos XML
    
      //Configurações Iniciais
      void setup(){
        size(displayWidth, displayHeight, JAVA2D); //Define tamanho da Janela, e forma de renderização
        background(255);     //Limpa tela
        smooth();            //Suaviza serrilhado nos contornos do desenho
        textFont(fontA, 40); //Define e de fonte e Tamanho
        fill(#1273C1);       //Seta cor para o Texto
    
        cp5_01 = new ControlP5(this); //Instancia objeto ControlP5 ( Biblioteca Gráfica )
        criaObjetos01();
        cursor(HAND);
      }
    
      //Loop enquanto rodar o programa
      void draw(){
        background(255);
        textFont(fontA, 40);
        fill(#1273C1);
        text("Paciente selecionado: " + nomePessoa, 20, 40);
      }
    
      void mouseMoved(){   
        //      
      }
    
      void mousePressed(){
        pressMouse = true;
      }
    
      void keyPressed() {
        retornaMenu();
      }
    
      void retornaMenu(){
        if (key == ESC ){
          key = 0;
          this.stop();
          this.dispose();
          frame.hide();
          frame       = null;
          cp5_01      = null;
          pressMouse = false;
        }
      }
    
      void criaObjetos01(){
    
        xml_01 = loadXML(PATHIMGMENUVIDEOS + "/" + idPessoa +"/pessoasMenuVideos.xml");
        XML[] children = xml_01.getChildren("menuVideo");
    
        for (int i = 0; i < children.length; i++) {
          String idImagem = children[i].getString("id");
    
          adicionaPosBtnXY(i, 1);
    
          cp5_01.addButton(idImagem)
                .setPosition(posBtnX, posBtnY)
                .setImages(loadImage(PATHIMGMENUVIDEOS+"/"+idPessoa+"/"+idImagem+"_0.jpg"), loadImage(PATHIMGMENUVIDEOS+"/"+idPessoa+"/"+idImagem+"_1.jpg"), loadImage(PATHIMGMENUVIDEOS+"/"+idPessoa+"/"+idImagem+"_2.jpg"))
                //.setCaptionLabel(idImagem)
                .setValue(int(idImagem))
                .updateSize();
        }//for
    
      }//função
    
      void controlEvent(ControlEvent theControlEvent) {
        if (pressMouse){
          int IDImagem = int(theControlEvent.controller().value());
          //imgPai = int(theControlEvent.controller().getLabel());
    
          excluiArquivo(IDImagem, PATHIMGMENUVIDEOS+"/"+idPessoa+"/"+IDImagem);
        }
      }
    
      void excluiArquivo(int IDImg, String pathArq){
        boolean excluiu = false;
        try{ 
          String fileName = dataPath(pathArq+"_0.jpg");
          File f = new File(fileName);
          if (f.exists()) {
            int resultMSG = MsgBox(2, "Deseja Excluir realmente o Link???", "CAL Anima ADM"); 
    
            if (resultMSG == 0){
              //Deleta Imagem
              f.delete();
              excluiArquivo2(PATHIMGMENUVIDEOS+"/"+idPessoa+"/"+IDImg+"_1.jpg");
              excluiArquivo2(PATHIMGMENUVIDEOS+"/"+idPessoa+"/"+IDImg+"_2.jpg");
    
              //Atualiza arquivo XML
              deletaXML(IDImg);
    
              excluiu = true;          
              MsgBox(1, "Link Excluído com Sucesso!!!", "CAL Anima ADM");
            } else {
              MsgBox(1, "Cancelado pelo Usuário!", "CAL Anima ADM");
            }
          }
        } catch (Exception e) {
          MsgBox(1, "Erro ao Gravar Imagem: " + e, "CAL Anima ADM");
        }  
        //println("Status " + excluiu);
        //return excluiu;
      }
    
      void excluiArquivo2(String pathArq){
        try{ 
          String fileName2 = dataPath(pathArq);
          File f2 = new File(fileName2);
    
          if (f2.exists()) {
            f2.delete();
          } else {
            MsgBox(1, "Não Encontrou arquivo imagem: " + pathArq, "CAL Anima ADM");
          }
        } catch (Exception e) {
          MsgBox(1, "Erro ao Excluir Imagem: " + e, "CAL Anima ADM");
        }
      }  
    
      void deletaXML(int IDImg) {
        xml_02 = loadXML(PATHIMGMENUVIDEOS+"/"+idPessoa +"/pessoasMenuVideos.xml");
        XML[] children2 = xml_02.getChildren("menuVideo");
    
        for (int i = 0; i < children2.length; i++) {
          if (children2[i].getContent().equals("video"+IDImg)) {
            xml_02.removeChild(children2[i]);
            saveXML(xml_02, dataPath(PATHIMGMENUVIDEOS+"/"+idPessoa)+"/pessoasMenuVideos.xml");     
            return; //Sair
          }//if
        }//for
      }//func 
    }
    
  • I'll leave the other part of the project as well, which can be useful for someone that can be adapted to build a menu with users or play for certain games, or other purposes.

    May not work because the files that need to load the Project (XML and TXT), I am leaving the print to get an idea of how it is.

    Thank you,

    //Importa Bibliotecas
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import java.awt.*;
    import java.io.File;
    import g4p_controls.*;
    import controlP5.*;
    
    //Declara Objetos
    ControlP5 cp5;
    GDropList dplPacientes;
    GLabel lblPaciente, lblURL, lblURLInfo, lblOpcImg;
    GButton btnCapturaIMG, btnCarregaIMG, btnCapturaURL, btnSalvarXML, btnSalvarIMG, btnRemoveItem;
    GOption optIMG1, optIMG2, optIMG3;
    GToggleGroup tg = new GToggleGroup();
    
    //Objeto XML
    XML xmlPacientes, xmlVideos;
    
    //Constantes
    static final String UNIDADE           = "D:";
    static final String PATHIMGPACIENTES  = UNIDADE + "/Projetos/Dados/ImgPacientes";
    static final String PATHIMGMENUVIDEOS = UNIDADE + "/Projetos/Dados/ImgMenuVideos";
    
    //Variáveis Globais
    static int idPessoa = 0;
    static int posBtnX, posBtnY;
    static boolean pressMouse = false;
    static PFont fontA;  //Define fonte padrão para o Projeto
    
    static String nomePessoa;
    
    //Variáveis
    String[] itens;
    String[] lines;
    String pastedMessage;
    
    int threshold    = 17;
    int mouseCounter = 0;
    int opcaoIMG     = 1;
    
    PImage imgPaciente;
    PImage pastedImage;
    PImage target;
    PImage destination;
    
    //Configurações Iniciais
    void setup() {
      size(800, 600, JAVA2D);
      frame.setTitle("C.A.L. Anima ADM - Manutenção de Imagens para Link de Vídeos"); //Título da aplicação na Janela do Windows
    
      //Define fonte para o Texto e seta cor
      fontA = loadFont("BuxtonSketch-48.vlw"); 
    
      //Instancia objetos
      cp5 = new ControlP5(this); 
    
      criaObjetos(); //Cria objetos tela ( GUI )
    }
    
    //Loop enquanto rodar o programa
    void draw() {
      background(#F3F0F7);
      fill(255);
    
      //Área da Foto
      stroke(0);
      rect(width-135, 10, 103, 121);
    
      //Área da Imagem
      noStroke();
      rect(10, 55, 640, 520);
    
      //Exibe imagem do Paciente
      if (imgPaciente != null)
        image(imgPaciente, width-134, 11);
    
      //Exibe url capturada
      if (pastedImage != null){
        image(pastedImage, 10, 60);
      }
    }
    
    //Evento de Teclado
    void keyPressed(){
      if (key == 0x16){ // Ctrl+v
        pastedMessage = GetTextFromClipboard();
        pastedImage   = GetImageFromClipboard();
        //println(GetTextFromClipboard());
      }
    }
    
    //Evento acionado ao Selecionar Item no Combo Box ( ou List Box )
    void handleDropListEvents(GDropList list, GEvent event) { 
      if (list == dplPacientes) {
        idPessoa   = int(list.getSelectedText().substring(0, 4));
        nomePessoa = list.getSelectedText();
        //println("Item: "+ dplPacientes.getSelectedIndex() + " - Texto: " + list.getSelectedText());
        println("Codigo/Nome: " + idPessoa + " - " + nomePessoa);  //
    
        if (idPessoa > 0){
          imgPaciente = loadImage(PATHIMGPACIENTES+"/"+idPessoa+".jpg");
          imgPaciente.resize(0,120);
    
          xmlVideos = loadXML(PATHIMGMENUVIDEOS+"/"+idPessoa+"/pessoasMenuVideos.xml");
        } else
          println("Código Paciente Inválido!");  
      }
    }
    
    //Evento acionado ao Clicar em um Botão
    void handleButtonEvents(GButton button, GEvent event) {
      // If we have more than one button then this is how we - check which one was cllicked.
      //if (button == btn01 && event == GEvent.CLICKED) {
      if ( event == GEvent.CLICKED){
        if (button == btnCapturaIMG){  
          pastedImage = GetImageFromClipboard();
    
          if (pastedImage != null){
            if (opcaoIMG == 1)
              pastedImage.resize(150,0);
            else if (opcaoIMG == 2)
              pastedImage.resize(400,0);
          } else {
            MsgBox(1, "Selecione uma imagem para Copiar!", "C.A.L. ADM"); 
          }
        } else if (button == btnCarregaIMG){
          selectInput("Selecione uma Imagem:", "fileSelected");
        } else if (button == btnCapturaURL){
          pastedMessage = GetTextFromClipboard();
    
          if (pastedMessage != null)
            lblURL.setText(pastedMessage);
          else
             MsgBox(1, "Selecione a URL para Gravar!", "C.A.L. ADM"); 
    
        } else if (button == btnSalvarXML){
          if (pastedImage != null && pastedMessage != null && idPessoa > 0){
    
            int resultMSG = MsgBox(2, "Salvar a Imagem para o Paciente?", "C.A.L. ADM"); 
    
            if (resultMSG == 0){
              try{
                size(pastedImage.width, pastedImage.height);
                background(255);
                image(pastedImage, 0, 0);
    
                int seqId = carregaSeq();
    
                salvaImagem(seqId);
                addChild("menuVideo", seqId, 1, pastedMessage, "video"+seqId);
    
                //Retona tamanho da Frame Original, e limpa a tela, para não gravar mais de uma vez, a mesma imagem
                size(800,600);                    
                pastedImage   = null;
                pastedMessage = null;
                lblURL.setText("");
                fill(255);
                stroke(0);
                rect(width-135, 10, 103, 121);
                MsgBox(1, "Imagem Gravada OK!", "CAL Anima - ADM");
              } catch (Exception e) {
                MsgBox(1, "Erro ao Gravar Imagem: " + e, "CAL Anima - ADM");
              }  
            } else {
              javax.swing.JOptionPane.showMessageDialog(null, "Cancelado pelo Usuário!");
            }
          } else {
            if (idPessoa == 0)
              MsgBox(1, "Selecione um Paciente para gravar a Imagem!", "CAL Anima - ADM");
    
            if (pastedImage == null)
              MsgBox(1, "Copie uma Imagem para ser gravada!", "CAL Anima - ADM"); 
    
            if (pastedMessage == null)
              MsgBox(1, "Copie a URL da imagem para ser gravada!", "CAL Anima - ADM"); 
          }
        } else if (button == btnRemoveItem){
          if (idPessoa > 0){
            int resultMSG = MsgBox(2, "Esta opção REMOVE opções de Link para Vídeos, Confirma a Visualização??", "C.A.L. ADM"); 
    
            if (resultMSG == 0){
              PApplet removeItem = new RemoveItem();
              runSketch(new String[] { "Remove Item Link de Vídeos" }, removeItem);
            } else {
              MsgBox(1, "Cancelado pelo Usuário! ", "CAL Anima - ADM");
            }
          } else {
            MsgBox(1, "Selecione um Paciente para excluir Links de Vídeos!", "CAL Anima - ADM");
          }
        }
      }
    }
    
    //Evento acionado quando seleciona objeto Option
    public void handleToggleControlEvents(GToggleControl option, GEvent event) {
      if (option == optIMG1)
        opcaoIMG = 1;
      else if (option == optIMG2)
        opcaoIMG = 2;
      else if (option == optIMG3)
        opcaoIMG = 3;
    
      //println("Opção Imagem: " + opcaoIMG);
    }
    
    //Retorna sequencia para imgagens
    int carregaSeq(){
      int sequencia = 0;
      //Carrega arquivo com a sequencia
      lines = loadStrings(PATHIMGMENUVIDEOS+"/"+idPessoa+"/arqSequencia.txt");
      sequencia = int(lines[0])+1;
    
      //Cria novo arquivo para salvar, atualizando a nova sequencia
      String[] list = split(Integer.toString(sequencia), ' ');
      saveStrings(PATHIMGMENUVIDEOS+"/"+idPessoa+"/arqSequencia.txt", list);
      return sequencia;
    }
    
    //Salva Imagens ( Principal e mais duas com filtros para efeito sobre o Botão )
    void salvaImagem(int seqId){
      //Salva imagem na pasta conforme paciente Selecionado
      saveFrame(PATHIMGMENUVIDEOS+"/"+idPessoa+"/"+seqId +"_0.jpg");
    
      //Cria duas cópias da Imagem, alterada por Filtro, para o efeito quando está sobre o ícone, ou quando clicar.
      target      = loadImage(PATHIMGMENUVIDEOS+"/"+idPessoa+"/"+seqId +"_0.jpg");
      destination = createImage(target.width, target.height, RGB);
      String seqImg;
    
      //percorre loop duas vezes, para criar as duas imagens, alterando o Filtro ( Preto e Branco ), tons mais claros e mais escuros
      for (int i = 0; i <= 1; i++){
        /**Program Filter Imagens Fonte:
           OpenProcessing Tweak of *@*http://www.openprocessing.org/sketch/49301*@* 
        **/
    
        target.loadPixels();
        destination.loadPixels();
    
        //Compare each pixel with its left neighbor, and take the difference of the pixel's .color attribute
        //the difference is compared to a threshold, and that threshold determines if the pixel is black or white
        //because we are looking at left neighbors, start at the second column (otherwise there is no left neighbor!)  
        for (int x = 1; x < width - 1; x++ ) {
          for (int y = 0; y < height; y++ ) {
            //snag the location and color of the target pixel
            int loc = x + y*target.width;
            color pix = target.pixels[loc];
            int leftLoc = (x - 1) + y*target.width;
            int rightLoc = (x + 1) + y*target.width;
            color leftColor = target.pixels[leftLoc];
            color rightColor = target.pixels[rightLoc];
    
            //Determine the difference between pixels
            float diff = abs(brightness(rightColor) - brightness(leftColor));
            //and compare it to a threshold.  All of the magic comes from varying this line.
            if (diff < threshold) {
              destination.pixels[loc] = color(255);
            } else {
              destination.pixels[loc] = color(0);
            }
          }
        }
    
        //Update the pixels in the destination file, show the image, and save it.
        destination.updatePixels();
        if (mouseCounter == 0) {
          image(destination,0,0);
        } else {
          image(target,0,0);
        }
    
        threshold = 7;
    
        if (i == 0) seqImg = "1";
        else seqImg = "2";
    
        saveFrame(PATHIMGMENUVIDEOS+"/"+idPessoa+"/"+seqId +"_"+seqImg+".jpg");
      }
    }
    
    //Adiciona Itens no arquivo XML
    void addChild( String unidade, int id, int opcLink, String urlLink, String seqVideo ) {
      //Add Child ( XML ) Font: Forum Processing
      XML newChild = xmlVideos.addChild(unidade);
    
      newChild.setContent(seqVideo);
      newChild.setInt("id", id);
      newChild.setInt("opcaoLink", opcLink);
      newChild.setString("linkURL", urlLink);
    
      saveXML(xmlVideos, dataPath(PATHIMGMENUVIDEOS+"/"+idPessoa)+"/pessoasMenuVideos.xml");
    }
    
    //Cria objetos Gráficos para montar tela
    void criaObjetos() {
      //Labels
      lblPaciente = new GLabel(this, 10, 5, 560, 20, "Pacientes:");
      lblPaciente.setFont(new Font("Arial", Font.PLAIN, 18));
      lblPaciente.setTextAlign(GAlign.LEFT, null);
    
      lblURLInfo = new GLabel(this, 10, height-25, 35, 30, "URL: ");
      lblURLInfo.setFont(new Font("Arial", Font.PLAIN, 12));
      lblURLInfo.setTextAlign(GAlign.LEFT, null);
    
      lblURL = new GLabel(this, 45, height-25, 560, 30, "");
      lblURL.setFont(new Font("Arial", Font.PLAIN, 12));
      lblURL.setTextAlign(GAlign.LEFT, null);
    
      //Botões
      btnCapturaIMG = new GButton(this, width-140, 140, 120, 30, "Capturar Imagem Vídeo");
      //btnCarregaIMG = new GButton(this, width-140, 180, 120, 30, "Carregar Imagem");
      btnCapturaURL = new GButton(this, width-140, 180, 120, 30, "Capturar URL Vídeo");
      //btnSalvarIMG  = new GButton(this, width-140, 260, 120, 30, "Salvar na Pasta");
      btnSalvarXML  = new GButton(this, width-140, 220, 120, 30, "Salvar");
      btnRemoveItem = new GButton(this, width-140, height-160, 120, 30, "Remover");
    
      //Label Opção Imagem
      lblOpcImg = new GLabel(this, width-140, 480, 150, 18, "Opções Imagem");
      lblOpcImg.setTextAlign(GAlign.LEFT, null);
      lblOpcImg.setTextBold();
    
      //Opções Imagem - Option
      optIMG1 = new GOption(this, width-140, 500, 200, 18, "Padrão Menu Menor");
      optIMG2 = new GOption(this, width-140, 520, 200, 18, "Padrão Menu Maior");
      optIMG3 = new GOption(this, width-140, 540, 200, 18, "Não alterar Tamanho");
      tg.addControls(optIMG1, optIMG2, optIMG3);
      optIMG1.setSelected(true);
    
      //Carrega XML com registros de Pacientes
      xmlPacientes = loadXML(PATHIMGPACIENTES + "/pessoas.xml");
      XML[] children = xmlPacientes.getChildren("pessoa");
    
      //Cria Array com registros do pacientes, para usar no Combo
      //itens = new String[] { "Selecione um Paciente", "1 - Paciente 1", "2 - Paciente 2", "3 - Paciente 3", "9 - Paciente Teste"}; 
      itens = new String[children.length+1];
      itens[0] = "Selecione um Paciente";
    
      //Carrega Itens no Array criado, conforme registros do XML
      for (int i = 0; i < children.length; i++) {
        itens[i+1] = children[i].getString("id")+" - "+children[i].getString("nomePessoa");
      } 
    
      //ComboBox - Lista com Nomes
      dplPacientes = new GDropList(this, 10, 27, width-165, 100, 5);
      dplPacientes.setItems(itens, 0);
      dplPacientes.setFont(new Font("Arial", Font.PLAIN, 14)); 
    }
    
    //Mostra Mensagens - Font: Forum Processing
    static int MsgBox(int optMSG, String Msg, String Title){
      int resultOpt;
    
      if (optMSG == 1){ 
        javax.swing.JOptionPane.showMessageDialog (null, Msg, Title, javax.swing.JOptionPane.INFORMATION_MESSAGE);
        resultOpt = 0;
      } else {
        resultOpt = javax.swing.JOptionPane.showConfirmDialog(null, Msg, Title, javax.swing.JOptionPane.YES_NO_OPTION);
      }
      //println("Opcao: " + resultOpt);
      return resultOpt;
    }
    
    //Captura Texto da área de transferência - Font: Forum Processing
    String GetTextFromClipboard(){
      String text = (String) GetFromClipboard(DataFlavor.stringFlavor);
      return text;
    }
    
    //Captura Imagem da área de transferência - Font: Forum Processing
    PImage GetImageFromClipboard(){
      PImage img           = null;
      java.awt.Image image = (java.awt.Image) GetFromClipboard(DataFlavor.imageFlavor);
    
      if (image != null){
        img = new PImage(image);
      }
      return img;
    }
    
    //Captura *** da área de transferência? - Font: Forum Processing
    Object GetFromClipboard(DataFlavor flavor){
      Clipboard clipboard   = getToolkit().getSystemClipboard();
      Transferable contents = clipboard.getContents(null);
      Object obj            = null;
    
      if (contents != null && contents.isDataFlavorSupported(flavor))  {
        try{
          obj = contents.getTransferData(flavor);
        }
        catch (UnsupportedFlavorException exu) // Unlikely but we must catch it
        {
         println("Unsupported flavor: " + exu);
         //~exu.printStackTrace();
        }
        catch (java.io.IOException exi)
        {
        println("Unavailable data: " + exi);
        //~   exi.printStackTrace();
        }
      }
      return obj;
    } 
    
    //Fazer melhoria, para carregar arquivos da pasta... font: Open Processing
    void fileSelected(File selection) {
      if (selection != null) {
        println(selection);
    
        //if(selection!=null){
          //pastedImage = loadImage(selection);
          //imgsized = target.get();
          //imgman = imgsized.get();
          //imgsized.resize(300,0);
          //image(imgsized,20,40);
          //imgman.resize(100,0);
          //image(target,350,160);
        //}
    
        //if(imgin!=null){
          //if(Save){
          //   output=selectOutput();
          //   if(output!=null){
          //     for(int x=0;x<imgsave.width; x++){
          //       for(int y=0; y<imgsave.height; y++){ 
          //         imgsave.save(output);
          //       }
          //       Save=false;
          //     }  
          //   }
        // }
      } else {  
        MsgBox(1, "Não carregada nenhuma Imagem!", "CAL Anima - ADM");
      }
    }
    
    static void adicionaPosBtnXY(int iPosBtn, int opc){
        if (iPosBtn == 0){ 
          //println("Primeiro Item: " + iPosBtn);
          posBtnX = 50;
          posBtnY = 100;
        } else {
          //println("Itens Posteriores: " + iPosBtn);
    
          if (opc == 1)
            posBtnX = posBtnX + 160;
          else
            posBtnX = posBtnX + 260; 
        }
      }
    
  • The images of how it's getting the project: Img01 img02

  • I don't have time, sorry

  • Hello, do not apologize for it, always grateful for the help I have in the forum ...

    Then I got a solution for when you remove the link, make the button is invisible, and when reload the menu, as it is no longer in the XML file, no longer appears in the menu.

    Need to replace this part of the code:

    void criaObjetos01(){
    
        xml_01 = loadXML(PATHIMGMENUVIDEOS + "/" + idPessoa +"/pessoasMenuVideos.xml");
        XML[] children = xml_01.getChildren("menuVideo");
    
        for (int i = 0; i < children.length; i++) {
          String idImagem = children[i].getString("id");
    
          adicionaPosBtnXY(i, 1);
    
          cp5_01.addButton("button"+idImagem)
                .setPosition(posBtnX, posBtnY)
                .setImages(loadImage(PATHIMGMENUVIDEOS+"/"+idPessoa+"/"+idImagem+"_0.jpg"), loadImage(PATHIMGMENUVIDEOS+"/"+idPessoa+"/"+idImagem+"_1.jpg"), loadImage(PATHIMGMENUVIDEOS+"/"+idPessoa+"/"+idImagem+"_2.jpg"))
                .setValue(int(idImagem))
                .updateSize();
        }//for
      }//função
    
      void controlEvent(ControlEvent theControlEvent) {
        if (pressMouse){
          int IDImagem     = int(theControlEvent.controller().value());
          String nomeBotao = theControlEvent.controller().name();
    
          excluiArquivo(IDImagem, PATHIMGMENUVIDEOS+"/"+idPessoa+"/"+IDImagem);
    
          //println(excluiu);
          if (excluiu){
            //if(theControlEvent.name().startsWith("button")) {
              cp5_01.getController(nomeBotao).setVisible(false);
            //}
          }
        }
      }
    

    Thank you for now, until the next challenge ... (laughs)

    Thank you

  • I thought about leaving the use of the program, ie in this program records the menus for each user, and in another, where other options, use what has been registered in this but do not know if it would be good idea ...

    If anyone needs something along those lines, and just leave any notification, which put the code here ...

    Thank you

  • This is the print images, use the program ...

    Obs .: I covered the images to preserve the identity of the patients ... Source of Images: Google Images att,

    img03 img04 img05

Sign In or Register to comment.