javahtmlwicketwicket-6

How to show label component when AjaxLink is clicked


When Ajaxlink is clicked, I need to display data from the JSON file. I have implemented the following code which is not working. Please correct my code if I did any mistake. (is it possible to add a label inside AjaxLink)

Thanks in advance.

AjaxLink<Void> jsonData = new AjaxLink<Void>("jsonData") {

            @Override
            public void onClick(AjaxRequestTarget target) {
                File jsonFile;
                try {
                    jsonFile = new File(fileLocation);

                ObjectMapper mapper = new ObjectMapper();
                JsonNode jsonNode = mapper.readValue(jsonFile, JsonNode.class);
                Label jsonLabel = new Label("jsonLabel",
                            mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode));
                jsonLabel.setOutputMarkupId(true);
                jsonLabel.setOutputMarkupPlaceholderTag(true);
                target.add(jsonLabel);
                addOrReplace(jsonLabel);
                } catch (JsonParseException e) {
                    e.printStackTrace();
                } catch (JsonMappingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        };

        add(jsonData);

Html:

               <div>
                    <a wicket:id="jsonData" class="text-white">View Template</a>
                    <pre wicket:id="jsonLabel" class="text-white bg-dark"> </pre>
                </div>

Solution

  • You need to add the Label as a sibling of the AjaxLink:

    final Label jsonLabel = new Label("jsonLabel", Model.of(""));
    jsonLabel.setOutputMarkupId(true);
    AjaxLink<Void> jsonData = new AjaxLink<Void>("jsonData") {
    
            @Override
            public void onClick(AjaxRequestTarget target) {
                File jsonFile;
                try {
                    jsonFile = new File(fileLocation);
    
                    ObjectMapper mapper = new ObjectMapper();        
                    JsonNode jsonNode = mapper.readValue(jsonFile, JsonNode.class);
                    // just update the Label's model and re-paint it
                    jsonLabel.setModelObject(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode));
                    target.add(jsonLabel);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    
        add(jsonData, jsonLabel);
    

    Your HTML is OK.