How do I add attributes to an XML elements in JDOM?

The program below will show you how to add attributes to an XML elements. Using JDOM library this can be easily done by calling the Element‘s setAttribute(String name, String value) method.

package org.kodejava.jdom;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class JDOMAddAttribute {
    public static void main(String[] args) {
        Document doc = new Document();
        Element root = new Element("root");

        // Create <row userid="alice"></row>
        Element child = new Element("row").setAttribute("userid", "alice");

        // Create <name firstname="Alice" lastname="Starbuzz"></name>
        Element name = new Element("name")
                .setAttribute("firstname", "Alice")
                .setAttribute("lastname", "Starbuzz");

        child.addContent(name);
        root.addContent(child);
        doc.addContent(root);

        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        try {
            outputter.output(doc, System.out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

And here goes the output:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <row userid="alice">
    <name firstname="Alice" lastname="Starbuzz" />
  </row>
</root>

Maven Dependencies

<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6.1</version>
</dependency>

Maven Central

How do I create an XML document using JDOM?

In this small program you can see how to use JDOM to create a simple xml file. Below you’ll see how to create elements of the xml document, set some text for the element.

After that you can see how to use the XMLOutputter class to write the JDOM document into file and display it on the screen. To make the output better we can apply a Format to our xml document.

package org.kodejava.jdom;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import java.io.FileWriter;

public class JDomCreatingXml {
    public static void main(String[] args) {
        // <rows>
        //     <row>
        //         <firstname>Alice</firstname>
        //         <lastname>Starbuzz</lastname>
        //         <address>Sunset Road</address>
        //     </row>
        // </row>
        Document document = new Document();
        Element root = new Element("rows");

        // Creating a child for the root element. Here we can see how to
        // set the text of an xml element.
        Element child = new Element("row");
        child.addContent(new Element("firstname").setText("Alice"));
        child.addContent(new Element("lastname").setText("Starbuzz"));
        child.addContent(new Element("address").setText("Sunset Road"));

        // Add the child to the root element and add the root element as
        // the document content.
        root.addContent(child);
        document.setContent(root);

        try {
            FileWriter writer = new FileWriter("userinfo.xml");
            XMLOutputter outputter = new XMLOutputter();

            // Set the XLMOutputter to pretty formatter. This formatter
            // use the TextMode.TRIM, which mean it will remove the
            // trailing white-spaces of both side (left and right)
            outputter.setFormat(Format.getPrettyFormat());

            // Write the document to a file and also display it on the
            // screen through System.out.
            outputter.output(document, writer);
            outputter.output(document, System.out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

This program will output the following XML document:

<?xml version="1.0" encoding="UTF-8"?>
<rows>
  <row>
    <firstname>Alice</firstname>
    <lastname>Starbuzz</lastname>
    <address>Sunset Road</address>
  </row>
</rows>

Maven Dependencies

<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6.1</version>
</dependency>

Maven Central

How do I create a Document object in JDOM?

The following example show you how to create a simple Document object in JDOM. We can create a new document directly by creating a new instance of the Document class, for additional information we can pass an Element as an argument.

To create a Document from an existing XML file we can use the SAXBuilder. Beside reading from file we can also build a Document from stream and URL.

package org.kodejava.jdom;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import java.io.File;

public class JDOMCreateDocument {
    public static void main(String[] args) {
        // Creating a document with an Element as the parameter.
        Element element = new Element("root");
        element.setText("Hello World");

        Document document = new Document(element);
        System.out.println("root.getName() = " +
                document.getRootElement().getName());

        // We can also create a document from a file, stream or URL using
        // a SAXBuilder
        SAXBuilder builder = new SAXBuilder();
        try {
            // Build a document from a file using a SAXBuilder.
            // The content of data.xml file:
            //
            // <?xml version="1.0" encoding="UTF-8"?>
            // <data>
            //     <row>
            //         <username>alice</username>
            //         <password>secret</password>
            //     </row>
            // </data>
            document = builder.build(new File("data.xml"));
            Element root = document.getRootElement();
            System.out.println("root.getName() = " + root.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6.1</version>
</dependency>

Maven Central

How do I get the items of a JList components?

In this example you can see how we can read the items of a JList component. We also obtain the size or the number of items in the JList components.

This can be done by calling JList‘s getModel() method which return a ListModel object. From the ListModel we can get the items size, and we can iterate the entire items of the JList component.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;
import java.text.DateFormatSymbols;

public class JListGetItems extends JFrame {
    public JListGetItems() {
        initialize();
    }

    public static void main(String[] args) {
        // Run the program, create a new instance of JListGetItems and
        // set its visibility to true.
        SwingUtilities.invokeLater(
                () -> new JListGetItems().setVisible(true));
    }

    private void initialize() {
        // Configure the frame default close operation, its size and the
        // layout.
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setSize(500, 500);
        this.setLayout(new BorderLayout(5, 5));

        // Create a JList and set the items to the available weekdays
        // names.
        Object[] listItems = DateFormatSymbols.getInstance().getWeekdays();
        JList<Object> list = new JList<>(listItems);
        getContentPane().add(list, BorderLayout.CENTER);

        // Below we start to print the size of the list items and iterates
        // the entire list items or elements.
        System.out.println("JList item size: " + list.getModel().getSize());

        System.out.println("Reading all JList items:");
        System.out.println("-----------------------");
        for (int i = 0; i < list.getModel().getSize(); i++) {
            Object item = list.getModel().getElementAt(i);
            System.out.println("Item = " + item);
        }
    }
}

And here is the result:

JList item size: 8
Reading all JList items:
-----------------------
Item = 
Item = Sunday
Item = Monday
Item = Tuesday
Item = Wednesday
Item = Thursday
Item = Friday
Item = Saturday

How do I set the cell width and height of a JList component?

The cell width and height of a JList can be defined by setting the fixedCellWidth and fixedCellHeight properties. These properties have a corresponding methods called setFixedCellWidth(int width) and setFixedCellHeight(int height).

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;
import java.util.Vector;

public class JListCellWidthAndHeight extends JFrame {
    public JListCellWidthAndHeight() {
        initialize();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new JListCellWidthAndHeight().setVisible(true));
    }

    private void initialize() {
        // Initialize windows default close operation, size and the layout
        // for laying the components.
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(500, 175);
        setLayout(new BorderLayout(5, 5));

        // Create a list of vector data to be used by the JList component.
        Vector<String> v = new Vector<>();
        v.add("A");
        v.add("B");
        v.add("C");
        v.add("D");

        JList<String> list = new JList<>(v);
        list.setFixedCellWidth(50);
        list.setFixedCellHeight(50);

        JScrollPane pane = new JScrollPane(list);

        // Add an action listener to the button to exit the application.
        JButton button = new JButton("CLOSE");
        button.addActionListener(e -> System.exit(0));

        // Add the scroll pane where the JList component is wrapped and
        // the button to the center and south of the panel
        getContentPane().add(pane, BorderLayout.CENTER);
        getContentPane().add(button, BorderLayout.SOUTH);
    }
}
JList Cell Width and Height Demo

JList Cell Width and Height Demo

How do I create a JList component?

JList is a component that displays a list of objects and allow user to select one or more items. To create an instance of JList we can pass a vector, an array of objects or a ListModel. In this example we will pass an array of objects that contains a date, string and numbers as the parameters.

By default, the list does not display a scrollbar. To give our JList component a scrollbar we must wrap it with a JScrollPane.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;
import java.util.Date;

public class CreateJListDemo extends JFrame {

    public CreateJListDemo() {
        initialize();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new CreateJListDemo().setVisible(true));
    }

    // Initialize the components and configuration of our CreateJListDemo.
    private void initialize() {
        // Define the window title, size and the default close operation.
        this.setTitle("Create JList Demo");
        this.setSize(500, 175);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        // Create an array of arbitrary objects for the JList to display.
        Object[] data = new Object[]{
                new Date(), "One", 1, Long.valueOf("12345"), "Four", "Five"
        };

        // Create an instance of JList and pass data variable as the
        // initial content of it. By default, the JList does not have a
        // scrolling behaviour, so we create a JScrollPane as the container
        // for the JList.
        JList<Object> list = new JList<>(data);
        JScrollPane scrollPane = new JScrollPane(list);

        // Add a button to close the program.
        JButton button = new JButton("Close");
        button.addActionListener(e -> System.exit(0));

        // Set the panel layout to BorderLayout and place the list in the
        // center and the button on the south.
        this.setLayout(new BorderLayout(5, 5));
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        getContentPane().add(button, BorderLayout.SOUTH);
    }
}
Swing JList Demo

Swing JList Demo

How do I get screen’s display mode information?

This example shows graphics devices display mode information such as the display width, height, refresh-rate and bit-depth. This information can be obtained from GraphicsDevice.getDisplayMode() method which return an instance of java.awt.DisplayMode.

We can also get the size of a screen using the following example How do I get my screen size?, but this example can handle only a single screen.

package org.kodejava.awt;

import java.awt.*;

public class GettingScreenDisplayModeInformation {
    public static void main(String[] args) {
        // Get local graphics environment
        GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();

        GraphicsDevice[] devices = env.getScreenDevices();

        int sequence = 1;
        for (GraphicsDevice device : devices) {
            System.out.println("Screen Number [" + (sequence++) + "]");
            System.out.println("Width       : " + device.getDisplayMode().getWidth());
            System.out.println("Height      : " + device.getDisplayMode().getHeight());
            System.out.println("Refresh Rate: " + device.getDisplayMode().getRefreshRate());
            System.out.println("Bit Depth   : " + device.getDisplayMode().getBitDepth());
            System.out.println();
        }
    }
}

An example of the program result:

Screen Number [1]
Width       : 2560
Height      : 1080
Refresh Rate: 60
Bit Depth   : 32

Screen Number [2]
Width       : 2560
Height      : 1080
Refresh Rate: 60
Bit Depth   : 32

How do I get number of available screens?

This code shows how to get number of available screen devices on the local machine or local graphics environment. We obtain the number of screens by getting the length of array returned by GraphicsEnvironment.getScreenDevices() method.

This process can produce a HeadlessException to happen if we try to run this code on a machine that doesn’t have a screen device with it.

package org.kodejava.awt;

import java.awt.GraphicsEnvironment;
import java.awt.GraphicsDevice;
import java.awt.HeadlessException;

public class GettingNumberOfScreen {
    public static void main(String[] args) {
        try {
            // Get local graphics environment
            GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();

            // Returns an array of all the screen GraphicsDevice objects.
            GraphicsDevice[] devices = env.getScreenDevices();

            int numberOfScreens = devices.length;
            System.out.println("Number of available screens = " + numberOfScreens);
        } catch (HeadlessException e) {
            // We'll get here if no screen devices was found.
            e.printStackTrace();
        }
    }
}

The output of the code snippet above:

Number of available screens = 2

How do I validate user’s password with PasswordEncryptor?

Every application that you’ll create may require an authentication process. This authentication process will at least contains a process of checking user’s login name and their password. To make the system reliable the password we usually stored the password in an encrypted form.

The BasicPasswordEncryptor which implements the PasswordEncryptor interface provide a BasicPasswordEncryptor.encryptPassword(String password) method for encrypting user’s password. To check if the user’s password is correct we use the BasicPasswordEncryptor.checkPassword(String plainText, String encryptedPassword) method.

package org.kodejava.jasypt;

import org.jasypt.util.password.BasicPasswordEncryptor;
import org.jasypt.util.password.PasswordEncryptor;

public class PasswordEncryptorDemo {
    public static void main(String[] args) {
        // Creates an instance of BasicPasswordEncryptor.
        PasswordEncryptor encryptor = new BasicPasswordEncryptor();

        // Encrypted version of user password.
        String encrypted = encryptor.encryptPassword("secret");
        System.out.println("encrypted = " + encrypted);

        // Compare user's plain text password with the encrypted one to check
        // if they are match.
        if (encryptor.checkPassword("secret", encrypted)) {
            System.out.println("Welcome to Jasypt");
        } else {
            System.out.println("Invalid secret word, access denied!");
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>org.jasypt</groupId>
    <artifactId>jasypt</artifactId>
    <version>1.9.3</version>
</dependency>

Maven Central

How do I create a message digest?

Creating a digest of a string message can be easily done using the general digester class Digester. First we need to get an instance of Digester, we call the class constructor and pass SHA-1 as the algorithm. After having a Digester instance we create the message digest by executing or calling the Digester.digest(byte[] binary) method of this class.

package org.kodejava.jasypt;

import org.jasypt.util.digest.Digester;

import java.util.Arrays;

public class DigesterDemo {
    public static void main(String[] args) {
        // Creates a new instance of Digester, using the SHA-1 algorithm.
        Digester digester = new Digester("SHA-1");

        byte[] message = "Hello World from Jasypt".getBytes();

        // Creates a digest from an array of byte message.
        byte[] digest = digester.digest(message);

        System.out.println("Digest = " + new String(digest));
        System.out.println("Digest = " + Arrays.toString(digest));
    }
}

Maven Dependencies

<dependency>
    <groupId>org.jasypt</groupId>
    <artifactId>jasypt</artifactId>
    <version>1.9.3</version>
</dependency>

Maven Central