0

I am new to java and trying following example. With the code below, I can print all nodes of a XML file. Now I would like to use Swing and put it out in a simple Swing window.

I understand how to create a window, but how can I connect the console output to a JTextArea? I searched for it on Stack Overflow, but did not get the right idea.

public static void main(String[] args) throws IOException 
{
    try  
    { 
        File file = new File("dum.xml");
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
        Document document = documentBuilder.parse(file); 
        System.out.println("Root element: "+ document.getDocumentElement().getNodeName()); 
        if (document.hasChildNodes())  
        { 
            printNodeList(document.getChildNodes());
        } 
    }  
    catch (Exception e) 
    { 
        System.out.println(e.getMessage()); 
    } 
} 

private static void printNodeList(NodeList nodeList) 
{ 
    for (int count = 0; count < nodeList.getLength(); count++)
    { 
        Node elemNode = nodeList.item(count); 
        if (elemNode.getNodeType() == Node.ELEMENT_NODE)  
        { 
            // get node name and value 
            System.out.println("\nZeilenname =" + elemNode.getNodeName()+ " [Anfang]");
            System.out.println("Zeileninhalt =" + elemNode.getTextContent()); 
            if (elemNode.hasAttributes())  
            {
                NamedNodeMap nodeMap = elemNode.getAttributes();
                for (int i = 0; i < nodeMap.getLength(); i++)
                {
                    Node node = nodeMap.item(i);
                    System.out.println("Attributname : " + node.getNodeName()); 
                    System.out.println("Attributwert : " + node.getNodeValue()); 
                }
            }
            if (elemNode.hasChildNodes())  
            {
                //recursive call if the node has child nodes
                printNodeList(elemNode.getChildNodes());
            }
            System.out.println("Zeilenname =" + elemNode.getNodeName()+ " [Ende]"); 
        }
    } 
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 3
    You don't need to redirect the console to a text area. All you need is to set the text to the Swing component instead of setting the text on the console. – hfontanez Nov 26 '21 at 14:52

2 Answers2

1

This is how to create the main frame for a Java Swing application following best practices (i.e. use SwingUtilities#invokeLater(...) to run your Swing application.

public class SwingDemo {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
    
    private static void createAndShowGUI() {
        JFrame f = new JFrame("Swing Demo");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(250,250);
        f.setVisible(true);
    }
}

Now you need to add the component to display text. JLabel, JTextField, and JTextAreaare the main candidates. Since you mentioned text area, let use that component. For that, all you need to do is add these two lines at the end:

    String text = "Hello World!";
    JTextArea textarea = new JTextArea();
    textarea.setText(text);
    f.add(textarea);
    textarea.append("\nI added this later"); // UPDATE

You can then modify this sample code so it looks better. For example, you can instead put the text area in a JPanel and you could then use layouts to control the placement and size of the panel in order to prevent the text area to expand to the size of the entire JFrame. But this minimalist code does exactly what you wanted, which is to set text in a Java Swing GUI.

UPDATE: You could use the append() method to add lines to your GUI. For example:

NamedNodeMap nodeMap = elemNode.getAttributes(); 
for (int i = 0; i < nodeMap.getLength(); i++)  
{ 
    Node node = nodeMap.item(i); 
    textarea.append("\nAttributname : " + node.getNodeName());
}
hfontanez
  • 5,774
  • 2
  • 25
  • 37
  • Thank you very much for the response. But I still dont understand how can I print out the node names , attributes name and values in the swing window. Shoud I use following statement: textarea.setText(nodeList)? – Javabeginner2021 Nov 26 '21 at 15:01
  • @Javabeginner2021 It all depends how you want the output to look. You could iterate thru your node list and set it to a `StringBuilder` and then set its text to the text area. I will suggest to experiment with different methods. If you have specific questions about handing of node lists, you could post a second question. But, to answer your question, no... you can't set the node list directly into the text area. You need to set its contents. – hfontanez Nov 26 '21 at 15:30
  • Please dont understand me wrong. I am very thankful for the quick response and you taking the time. I am not asking to solve the problem but your answers are very vague. So with my knowledge it doesnt really help to fill the gap – Javabeginner2021 Nov 26 '21 at 16:31
  • @Javabeginner2021 I appreciate your comments, but the answer is not vague. It is only vague to you because you lack certain knowledge; which I mean no disrespect to you by saying this. In your code, you call methods like `elemNode.getNodeName()` to set the String (text) to the console. You must do the same to set text in the text area. That said, I will make an update to my post to show you how to append text to the same component. – hfontanez Nov 26 '21 at 16:59
1

Create a JTextArea. Replace all calls to System.out.println with JTextArea.append. Below code demonstrates.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.File;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XmlSwing {
    private JTextArea textArea;

    private void createAndDisplayGui() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(createTextArea(), BorderLayout.CENTER);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JScrollPane createTextArea() {
        textArea = new JTextArea(20, 40);
        createTextAreaText();
        JScrollPane scrollPane = new JScrollPane(textArea);
        return scrollPane;
    }

    private void createTextAreaText() {
        try {
            File file = new File("dum.xml");
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document document = documentBuilder.parse(file);
            textArea.append("Root element: " + document.getDocumentElement().getNodeName() + "\n");
            if (document.hasChildNodes()) {
                printNodeList(document.getChildNodes());
            }
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    private void printNodeList(NodeList nodeList) {
        for (int count = 0; count < nodeList.getLength(); count++) {
            Node elemNode = nodeList.item(count);
            if (elemNode.getNodeType() == Node.ELEMENT_NODE) {
                // get node name and value
                textArea.append("\nZeilenname =" + elemNode.getNodeName() + " [Anfang]\n");
                textArea.append("Zeileninhalt =" + elemNode.getTextContent() + "\n");
                if (elemNode.hasAttributes()) {
                    NamedNodeMap nodeMap = elemNode.getAttributes();
                    for (int i = 0; i < nodeMap.getLength(); i++) {
                        Node node = nodeMap.item(i);
                        textArea.append("Attributname : " + node.getNodeName() + "\n");
                        textArea.append("Attributwert : " + node.getNodeValue() + "\n");
                    }
                }
                if (elemNode.hasChildNodes()) {
                    // recursive call if the node has child nodes
                    printNodeList(elemNode.getChildNodes());
                }
                textArea.append("Zeilenname =" + elemNode.getNodeName() + " [Ende]\n");
            }
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new XmlSwing().createAndDisplayGui());
    }
}

Refer to Creating a GUI With Swing

Abra
  • 19,142
  • 7
  • 29
  • 41