How do I right justified JTextField contents?

To right justified a JTextField contents we can call the setHorizontalAlignment(JTextField.RIGHT) method of the JTextField class.

package org.kodejava.swing;

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

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

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

    private void initComponents() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(500, 500);

        Container container = getContentPane();
        container.setLayout(new FlowLayout(FlowLayout.LEFT));

        JTextField textField = new JTextField(15);
        textField.setPreferredSize(new Dimension(100, 20));

        // Right justify the JTextField contents
        textField.setHorizontalAlignment(JTextField.RIGHT);

        container.add(textField);
    }
}

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