How do I sort strings data using CollationKey class?

When the strings must be compared multiple times, for example when sorting a list of strings. It’s more efficient to use CollationKey class. Using CollationKey to compare strings is generally faster than using Collator.compare().

You can not create CollationKey directly. Rather, generate them by calling Collator.getCollationKey() method. You can only compare CollationKey generated from the same Collator object.

package org.kodejava.text;

import java.text.CollationKey;
import java.text.Collator;
import java.util.Arrays;

public class CollationKeyExample {
    public static void main(String[] args) {
        String[] countries = {
                "German",
                "United Kingdom",
                "United States",
                "French",
                "Japan",
                "Myanmar",
                "India"
        };

        System.out.println("original:");
        System.out.println(Arrays.toString(countries));

        // Gets Collator object of default locale
        Collator collator = Collator.getInstance();

        // Creates and initializes CollationKey array
        CollationKey[] keys = new CollationKey[countries.length];

        for (int i = 0; i < countries.length; i++) {
            // Generate CollationKey by calling
            // Collator.getCollationKey() method then assign into
            // keys which is an array of CollationKey.
            // The CollationKey for the given String based on the 
            // Collator's collation rules.
            keys[i] = collator.getCollationKey(countries[i]);
        }

        // Sort the keys array
        Arrays.sort(keys);

        // Print out the sorted array
        System.out.println("sorted result: ");
        StringBuilder sb = new StringBuilder();
        for (CollationKey key : keys) {
            sb.append(key.getSourceString()).append(",");
        }
        System.out.println(sb);
    }
}

Below is the result of the program:

original:
[German, United Kingdom, United States, French, Japan, Myanmar, India]
sorted result: 
French,German,India,Japan,Myanmar,United Kingdom,United States,

How do I sort an array of string data using RuleBasedCollator class?

We can use the java.text.Collator class to sort strings in language-specific order. Using the java.text.Collator class makes the string not just sorted by the ASCII code of their characters, but it will follow the language natural order of the characters.

If the predefined collation rules do not meet your needs, you can design your own rules and assign them to a RuleBasedCollator object. Customized collation rules are contained in a String object that is passed to the RuleBasedCollator constructor.

package org.kodejava.text;

import java.text.ParseException;
import java.text.RuleBasedCollator;
import java.util.Arrays;

public class RuleBasedCollatorDemo {
    public static void main(String[] args) {
        String rule1 = ("< a < b < c");
        String rule2 = ("< c < b < a");
        String rule3 = ("< c < a < b");

        String[] words = {
                "apple",
                "banana",
                "carrot",
                "apricot",
                "blueberry",
                "cabbage"
        };

        try {
            RuleBasedCollator rb1 = new RuleBasedCollator(rule1);
            RuleBasedCollator rb2 = new RuleBasedCollator(rule2);
            RuleBasedCollator rb3 = new RuleBasedCollator(rule3);

            System.out.println("original: ");
            System.out.println(Arrays.toString(words));

            // Sort based on rule1
            Arrays.sort(words, rb1);
            System.out.println("rule: " + rb1.getRules());
            System.out.println(Arrays.toString(words));

            // Sort based on rule2
            Arrays.sort(words, rb2);
            System.out.println("rule: " + rb2.getRules());
            System.out.println(Arrays.toString(words));

            // Sort based on rule3
            Arrays.sort(words, rb3);
            System.out.println("rule: " + rb3.getRules());
            System.out.println(Arrays.toString(words));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

Below is the result of sorting strings using a different RuleBasedCollator

original: 
[apple, banana, carrot, apricot, blueberry, cabbage]
rule: < a < b < c
[apple, apricot, banana, blueberry, cabbage, carrot]
rule: < c < b < a
[cabbage, carrot, banana, blueberry, apple, apricot]
rule: < c < a < b
[cabbage, carrot, apple, apricot, banana, blueberry]

How do I set the initial color of a JColorChooser?

To create an instance of a JColorChooser with a default or initial color such as Color.BLUE you can pass the Color object to the constructor of the JColorChooser component. The example below shows how to do it.

package org.kodejava.swing;

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

public class JColorChooserDefaultColor extends JFrame {
    public JColorChooserDefaultColor() throws HeadlessException {
        initializeUI();
    }

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

    private void initializeUI() {
        setTitle("JColorChooser Demo");
        setLayout(new BorderLayout());
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        // Creates an instance of JColorChooser and set Color.BLUE
        // as the default selected color.
        JColorChooser jcc = new JColorChooser(Color.BLUE);

        getContentPane().add(jcc, BorderLayout.CENTER);
        this.pack();
    }
}

JColorChooser Initial Color

How do I get the selected color from JColorChooser?

To get the selected color from JColorChooser we need to create an implementation of the ChangeListener interface. This interface provides a single method call stateChanged(ChangeEvent e). The instance of this interface implementation need to be passed to JColorChooser by calling the JColorChooser.getSelectionModel().addChangeListener() method.

In this example our ChangeListener implementation get the selected color and replace the foreground color the JLabel component.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;

public class JColorChooserColorSelection extends JFrame {
    private JColorChooser jcc = null;
    private JLabel label = null;

    public JColorChooserColorSelection() {
        initializeUI();
    }

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

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

        jcc = new JColorChooser();
        jcc.getSelectionModel().addChangeListener(new ColorSelection());
        getContentPane().add(jcc, BorderLayout.PAGE_START);

        label = new JLabel("Selected Font Color", JLabel.CENTER);
        label.setFont(new Font("SansSerif", Font.BOLD, 24));
        label.setForeground(Color.BLACK);
        label.setPreferredSize(new Dimension(100, 100));
        getContentPane().add(label, BorderLayout.CENTER);
        this.pack();
    }

    /**
     * A ChangeListener implementation for listening the color
     * selection of the JColorChooser component.
     */
    class ColorSelection implements ChangeListener {
        public void stateChanged(ChangeEvent e) {
            Color color = jcc.getColor();
            label.setForeground(color);
        }
    }
}

JColorChooser get selected color

How do I use JColorChooser component?

The JColorChooser is a Swing component that provides a palette from where we can select a color code in RGB format. The JColorChooser component has two parts, the tabbed pane of color selection and a preview box. The tabbed has three tabs which allows us to select a color from a swatches, a HSB (Hue, Saturation and Brightness) combination and an RGB (Red Blue Green) color combination.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;

public class JColorChooserDemo extends JFrame implements ChangeListener {
    private JColorChooser colorChooser = null;

    public JColorChooserDemo() throws HeadlessException {
        initUI();
    }

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

    private void initUI() {
        // Set title and default close operation of this JFrame.
        setTitle("JColorChooser Demo");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // Creates an instance of JColorChooser component and
        // adds it to the frame's content.
        colorChooser = new JColorChooser();
        getContentPane().add(colorChooser, BorderLayout.PAGE_END);

        // Add a change listener to get the selected color in this
        // JColorChooser component.
        colorChooser.getSelectionModel().addChangeListener(this);
        this.pack();
    }

    /**
     * Handles color selection in the JColorChooser component.
     *
     * @param e the ChangeEvent
     */
    public void stateChanged(ChangeEvent e) {
        // Get the selected color in the JColorChooser component
        // and print the color in RGB format to the console.
        Color color = colorChooser.getColor();
        System.out.println("color = " + color);
    }
}

When you run the program above a frame with JColorChooser component will be shown. A string of the color code in an RGB format will be printed in the console if you click a color from the color selection.

Here is an image of a JColorChooser component.

JColorChooser Component Demo