How do I format JLabel using HTML?

JLabel text can be formatted using an HTML standard tags. The example below shows you how we can use and HTML font tag to change the font size, color and style of JLabel text.

package org.kodejava.swing;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.Container;
import java.awt.FlowLayout;

public class JLabelHTMLStyle extends JFrame {
    public JLabelHTMLStyle() {
        setTitle("JLabel with HTML Style");
        initComponents();
    }

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

    private void initComponents() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(500, 500);
        Container container = getContentPane();
        container.setLayout(new FlowLayout(FlowLayout.CENTER));

        // Create a JLabel object that display a string formatted using HTML.
        // 14 font size with red and italic.
        String text = "<html>" +
            "<font size='16' color='orange'><strong>Hello World!</strong></font>" +
            "</html>";
        JLabel label = new JLabel(text);
        container.add(label);
    }
}
JLabel with HTML Style

JLabel with HTML Style

How do I get an exception stack trace message?

In this example we use the java.io.StringWriter and java.io.PrintWriter class to convert stack trace exception message to a string.

package org.kodejava.io;

import java.io.StringWriter;
import java.io.PrintWriter;

public class StackTraceToString {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (Exception e) {
            // Create a StringWriter and a PrintWriter both of these object
            // will be used to convert the data in the stack trace to a string.
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);

            // Instead of writing the stack trace in the console we write it
            // to the PrintWriter, to get the stack trace message we then call
            // the toString() method of StringWriter.
            e.printStackTrace(printWriter);

            System.out.println("Error = " + stringWriter);
        }
    }
}

This code snippet print the following output:

Error = java.lang.ArithmeticException: / by zero
    at org.kodejava.io.StackTraceToString.main(StackTraceToString.java:9)

How do I read and write data in Windows registry?

The java.util.prefs package provides a way for applications to store and retrieve user and system preferences and data configuration. These preference data will be stored persistently in an implementation-dependent backing stored. For example in Windows operating system in will stored in Windows registry.

To write and read these data we use the java.util.prefs.Preferences class. The following example will show you how to read and write to the HKCU (HKEY_CURRENT_USER) in the registry.

package org.kodejava.util.prefs;

import java.util.prefs.Preferences;

public class RegistryDemo {
    public static final String PREF_KEY = "kodejava";
    public static void main(String[] args) {
        // Write Preferences information to HKCU (HKEY_CURRENT_USER),
        // HKCU\SOFTWARE\JavaSoft\Prefs
        Preferences userPref = Preferences.userRoot();
        userPref.put(PREF_KEY, "https://kodejava.org");

        // Below we read back the value we've written in the code above.
        System.out.println("Preferences = "
                + userPref.get(PREF_KEY, PREF_KEY + " was not found."));
    }
}

How do I display an image in JButton?

package org.kodejava.swing;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.FlowLayout;

public class ButtonImageExample extends JFrame {
    public ButtonImageExample() {
        initComponents();
    }

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

    private void initComponents() {
        setTitle("My Buttons");
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));

        // Creates two JButton object with an images to display. The image can be
        // a gif, jpeg, png and some other type supported. And we also set the
        // mnemonic character of the button for short-cut key.
        JButton okButton = new JButton("OK", new ImageIcon(
                this.getClass().getResource("/images/ok.png")));
        okButton.setMnemonic('O');
        JButton cancelButton = new JButton("Cancel", new ImageIcon(
                this.getClass().getResource("/images/cancel.png")));
        cancelButton.setMnemonic('C');

        getContentPane().add(okButton);
        getContentPane().add(cancelButton);
    }
}
JButton with Image Icon

JButton with Image Icon

How do I use JFormattedTextField to format user input?

The JFormattedTextField allows us to create a text field that can accept a formatted input. In this code snippet we create two formatted text fields that accept a valid phone number and a date.

package org.kodejava.swing;

import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.text.DateFormatter;
import javax.swing.text.MaskFormatter;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FormattedTextFieldExample extends JFrame {
    public FormattedTextFieldExample() {
        initComponents();
    }

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

    private void initComponents() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setTitle("Format User Input");
        setSize(new Dimension(500, 500));
        getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));

        MaskFormatter mask = null;
        try {
            // Create a MaskFormatter for accepting phone number, the # symbol accept
            // only a number. We can also set the empty value with a place holder
            // character.
            mask = new MaskFormatter("(###) ###-####");
            mask.setPlaceholderCharacter('_');
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // Create a formatted text field that accept a valid phone number.
        JFormattedTextField phoneField = new JFormattedTextField(mask);
        phoneField.setPreferredSize(new Dimension(100, 20));

        // Here we create a formatted text field that accept a date value. We
        // create an instance of SimpleDateFormat and use it to create a
        // DateFormatter instance which will be passed to the JFormattedTextField.
        DateFormat format = new SimpleDateFormat("dd-MMMM-yyyy");
        DateFormatter df = new DateFormatter(format);
        JFormattedTextField dateField = new JFormattedTextField(df);
        dateField.setPreferredSize(new Dimension(100, 20));
        dateField.setValue(new Date());

        getContentPane().add(phoneField);
        getContentPane().add(dateField);
    }
}
User Input Format

User Input Format

Here are some other characters that can be used in the MaskFormatter class.

Char Description
# For number
? For letter
A For number or letter
* For anything
L For letter, it will be converted to the equivalent lower case
U For letter, it will be converted to the equivalent upper case
H For hexadecimal value
To escape another mask character