How do I create JSpinner component with date value?

The SpinnerDateModel allow us to display and select date information from the JSpinner component. By default, the initial value of the model will be set to the current date. To change it we can call the setValue method of the JSpinner object.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;
import java.util.GregorianCalendar;
import java.util.Calendar;

public class JSpinnerDate extends JFrame {
    public JSpinnerDate() {
        initializeUI();
    }

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

    private void initializeUI() {
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // Create a SpinnerDateModel with current date as the initial value.
        SpinnerDateModel model = new SpinnerDateModel();

        // Set the spinner value to October 9, 2021.
        JSpinner spinner = new JSpinner(model);
        Calendar calendar = new GregorianCalendar(2021, Calendar.OCTOBER, 9);
        spinner.setValue(calendar.getTime());

        getContentPane().add(spinner, BorderLayout.NORTH);
    }
}

How do I create a JSpinner with a SpinnerListModel?

This example show you how to create a JSpinner component and pass a SpinnerListModel as the available values of the JSpinner component. The SpinnerListModel can hold a value of collections object and a simple array of object instance.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class JSpinnerCreateDemo extends JFrame {
    public JSpinnerCreateDemo() {
        initializeUI();
    }

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

    private void initializeUI() {
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // Creating an array of color name that we'll use as the
        // source of our SpinnerListMode.
        String[] colors = new String[]{
                "Red", "Orange", "Yellow", "Green", "Blue", "Purple"
        };
        SpinnerListModel model = new SpinnerListModel(colors);

        // Create a JSpinner instance with a spinner model as the value.
        // This JSpinner will allow us to select a colour name when we
        // press the JButton below.
        final JSpinner spinner = new JSpinner(model);
        getContentPane().add(spinner, BorderLayout.NORTH);

        JButton okButton = new JButton("OK");
        okButton.addActionListener(e -> {
            String color = (String) spinner.getValue();
            System.out.println("Color = " + color);
        });
        getContentPane().add(okButton, BorderLayout.SOUTH);
    }
}

How do I create a JSpinner component?

JSpinner is a single line input field with two buttons (arrow up and arrow down) that allow us to select a value like number or object from a sequence value. It looks like a combobox without a drop-down.

In the following example we create the default JSpinner that will give us a spinner to select an integer value from it.

package org.kodejava.swing;

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

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

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

    private void initialize() {
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // Create an instance of JSpinner and put it at the top of the frame.
        final JSpinner spinner = new JSpinner();
        getContentPane().add(spinner, BorderLayout.NORTH);

        // Create a JButton and print out the value of the JSpinner when
        // the button is clicked.
        JButton okButton = new JButton("OK");
        okButton.addActionListener(e -> {
            Integer value = (Integer) spinner.getValue();
            System.out.println("value = " + value);
        });
        getContentPane().add(okButton, BorderLayout.SOUTH);
    }
}

How do I get mixed content of an XML element in JDOM?

The following example demonstrates how to read mixed content of an xml element. A mixed content can have more than one type of content such as text (Text), comment (Comment), CDATA (CDATA) or some child elements (Element).

You also see that we can remove the mixed content from the element by calling the remove method of the List just like what we do with a collection of data.

package org.kodejava.jdom;

import org.jdom2.*;
import org.jdom2.input.SAXBuilder;

import java.io.IOException;
import java.io.StringReader;
import java.util.List;

public class JDOMMixedContent {
    public static void main(String[] args) {
        String xml = """
                <root> \
                    <data> \
                        <!-- This element contains application data --> \
                        User Information \
                        <![CDATA[<table><tr><td>-data-</td></tr></table>]]> \
                        <field name="username">alice</field> \
                    </data> \
                </root>""";

        SAXBuilder builder = new SAXBuilder();
        try {
            Document document = builder.build(new StringReader(xml));
            Element root = document.getRootElement();
            Element data = root.getChild("data");

            // Reading the mixed content of an xml element and iterate
            // the result list. This list object can contain any of the
            // following objects: Comment, Element, CDATA, DocType,
            // ProcessingInstruction, EntityRef and Text.
            List<Content> contents = data.getContent();

            for (Content content : contents) {
                if (content instanceof Comment comment) {
                    System.out.println("Comment   = " + comment);
                } else if (content instanceof Element element) {
                    System.out.println("Element   = " + element);
                } else if (content instanceof CDATA cdata) {
                    System.out.println("CDATA     = " + cdata);
                } else if (content instanceof DocType docType) {
                    System.out.println("DocType   = " + docType);
                } else if (content instanceof ProcessingInstruction pi) {
                    System.out.println("PI        = " + pi);
                } else if (content instanceof EntityRef entityRef) {
                    System.out.println("EntityRef = " + entityRef);
                } else if (content instanceof Text text) {
                    System.out.println("Text      = " + text);
                }
            }

            // Remove the second mixed contents which is the CDATA contents.
            contents.remove(2);
        } catch (JDOMException | IOException e) {
            e.printStackTrace();
        }
    }
}

Here are the result of our program:

Text      = [Text:          ]
Comment   = [Comment: <!-- This element contains application data -->]
Text      = [Text:          User Information         ]
CDATA     = [CDATA: <table><tr><td>-data-</td></tr></table>]
Text      = [Text:          ]
Element   = [Element: <field/>]
Text      = [Text:      ]

Maven Dependencies

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

Maven Central

How do I build XML CDATA sections in JDOM?

This example demonstrates how to add CDATA section into an xml document. A CDATA section indicates a block that shouldn’t be parsed. To build a CDATA section just wrap the string with a CDATA object.

package org.kodejava.jdom;

import org.jdom2.CDATA;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import java.io.IOException;
import java.io.StringReader;

public class JDOMBuildCDATASection {
    public static void main(String[] args) {
        String xml = """
                <root>
                   <comments>
                       <comment></comment>
                   </comments>
                </root>""";

        SAXBuilder builder = new SAXBuilder();
        try {
            Document document = builder.build(new StringReader(xml));
            Element root = document.getRootElement();
            Element comments = root.getChild("comments");

            Element comment = comments.getChild("comment");

            // Using the setContent and addContent to add CDATA section
            // into  the xml element.
            comment.setContent(
                    new CDATA("<b>This is a bold string</b>."));
            comment.addContent(
                    new CDATA("<i>And this an italic string</i>."));

            XMLOutputter outputter =
                    new XMLOutputter(Format.getPrettyFormat());
            outputter.output(document, System.out);

            // Reading a CDATA section is simply done by calling the 
            // getText method. It doesn't care if it was a simple string
            // or a CDATA section, it will just return the content as 
            // string.
            String text = comment.getText();
            System.out.println("Text = " + text);
        } catch (JDOMException | IOException e) {
            e.printStackTrace();
        }
    }
}

The output of the code snippet above:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <comments>
    <comment><![CDATA[<b>This is a bold string</b>.]]><![CDATA[<i>And this an italic string</i>.]]></comment>
  </comments>
</root>
Text = <b>This is a bold string</b>.<i>And this an italic string</i>.

Maven Dependencies

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

Maven Central