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

How do I make updates in updatable ResultSet?

Using an updatable result set enables our program to update record in the database from the ResultSet object. The operation on the ResultSet object can be updated, inserted or deleted. With this mechanism, we can update a database without executing a query.

In the example below we have a product table with the id, code, name, and price columns. In the first step after we load the result set, we update the product name of the first record. Then we move to the next record and delete it. At last, we insert a new record to a database.

package org.kodejava.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class UpdatableResultSetDemo {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    public static void main(String[] args) {
        try (Connection connection =
                     DriverManager.getConnection(URL, USERNAME, PASSWORD)) {

            // Create an updatable result set. It means that instead of
            // using a separate sql command to update the data, we can
            // update it directly in the result set object.
            //
            // What makes it updatable is because, when creating the
            // statement, we ask the connection object to create a statement
            // with CONCUR_UPDATABLE. The updatable doesn't need to be
            // TYPE_SCROLL_SENSITIVE, but adding this parameter to the
            // statement enables us to go back and forth to update the data.
            Statement statement = connection.createStatement(
                    ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

            String query = "SELECT id, code, name, price FROM product";
            ResultSet rs = statement.executeQuery(query);

            System.out.println("id\tcode\tname\tprice");

            while (rs.next()) {
                System.out.println(rs.getLong("id") + "\t"
                                   + rs.getString("code") + "\t"
                                   + rs.getString("name") + "\t"
                                   + rs.getDouble("price"));
            }

            // Move to the first row and update the result set data. After
            // we update the row value, we call the updateRow() method to
            // update the data in the database.
            rs.first();
            rs.updateString("name", "UML Distilled 3rd Edition");
            rs.updateRow();

            // Move to the next result set row and delete the row in the
            // result set and apply it to the database.
            rs.next();
            rs.deleteRow();

            // Insert a new row in the result set object with the
            // moveToInsertRow() method. Supply the information to be
            // inserted and finally call the insertRow() method to insert
            // record to the database.
            rs.moveToInsertRow();
            rs.updateString("code", "P0000010");
            rs.updateString("name", "Data Structures, Algorithms");
            rs.updateDouble("price", 50.99);
            rs.insertRow();

            rs.beforeFirst();
            System.out.println();
            System.out.println("id\tcode\tname\tprice");

            while (rs.next()) {
                System.out.println(rs.getLong("id") + "\t"
                                   + rs.getString("code") + "\t"
                                   + rs.getString("name") + "\t"
                                   + rs.getDouble("price"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

The code snippet prints out the following output:

id  code    name    price
1   P0000001    Java 2 Notebook 25.0
2   P0000002    Java Servlet Programming    30.0
3   P0000003    PHP Programming 20.0
4   P0000004    Longman Active Study Dictionary 40.0
5   P0000005    Ruby on Rails   24.0
6   P0000006    Championship Manager    0.0
7   P0000007    Transport Tycoon Deluxe 0.0
8   P0000008    Roller Coaster Tycoon 3 0.0
9   P0000009    Pro Evolution Soccer    0.0

id  code    name    price
1   P0000001    UML Distilled 3rd Edition   25.0
3   P0000003    PHP Programming 20.0
4   P0000004    Longman Active Study Dictionary 40.0
5   P0000005    Ruby on Rails   24.0
6   P0000006    Championship Manager    0.0
7   P0000007    Transport Tycoon Deluxe 0.0
8   P0000008    Roller Coaster Tycoon 3 0.0
9   P0000009    Pro Evolution Soccer    0.0
10  P0000010    Data Structures, Algorithms 50.99

Maven Dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
</dependency>

Maven Central

How do I handle mouse button click event?

package org.kodejava.swing;

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

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

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

    private void initComponents() {
        setTitle("Handling Mouse Click Event");
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        final JTextArea textArea = new JTextArea();
        textArea.setText("Click Me!");

        textArea.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.NOBUTTON) {
                    textArea.setText("No button clicked" + "\n");
                } else if (e.getButton() == MouseEvent.BUTTON1) {
                    textArea.setText("Button 1 clicked" + "\n");
                } else if (e.getButton() == MouseEvent.BUTTON2) {
                    textArea.setText("Button 2 clicked" + "\n");
                } else if (e.getButton() == MouseEvent.BUTTON3) {
                    textArea.setText("Button 3 clicked" + "\n");
                }

                textArea.append("Number of click: " + e.getClickCount() + "\n");
                textArea.append("Click position (X, Y):  " + e.getX() + ", " + e.getY());
            }
        });

        getContentPane().add(textArea);
    }
}
Handling Mouse Click Event

Handling Mouse Click Event

How do I handle mouse wheel event?

package org.kodejava.swing;

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.event.MouseWheelEvent;

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

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

    private void initComponents() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setTitle("Mouse Wheel Listener Demo");
        setSize(500, 500);

        JTextArea textArea = new JTextArea();
        textArea.addMouseWheelListener(e -> {
            System.out.println("MouseWheelListenerDemo.mouseWheelMoved");

            // If wheel rotation value is a negative it means rotate up, while
            // positive value means rotate down
            if (e.getWheelRotation() < 0) {
                System.out.println("Rotated Up... " + e.getWheelRotation());
            } else {
                System.out.println("Rotated Down... " + e.getWheelRotation());
            }

            // Get scrolled unit amount
            System.out.println("ScrollAmount: " + e.getScrollAmount());

            // WHEEL_UNIT_SCROLL representing scroll by unit such as the
            // arrow keys. WHEEL_BLOCK_SCROLL representing scroll by block
            // such as the page-up or page-down key.
            if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) {
                System.out.println("MouseWheelEvent.WHEEL_UNIT_SCROLL");
            }

            if (e.getScrollType() == MouseWheelEvent.WHEEL_BLOCK_SCROLL) {
                System.out.println("MouseWheelEvent.WHEEL_BLOCK_SCROLL");
            }
        });

        getContentPane().add(textArea);
    }
}

The scrolling the mouse wheel the code snippet will print something like:

MouseWheelListenerDemo.mouseWheelMoved
Rotated Down... 1
ScrollAmount: 3
MouseWheelEvent.WHEEL_UNIT_SCROLL
MouseWheelListenerDemo.mouseWheelMoved
Rotated Up... -1
ScrollAmount: 3
MouseWheelEvent.WHEEL_UNIT_SCROLL

How do I handle mouse motion event?

package org.kodejava.swing;

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

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

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

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

        JTextArea textArea = new JTextArea("Hello World... try to move the mouse, click and drag it...");
        textArea.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                System.out.println("Mouse Dragged...");
            }

            public void mouseMoved(MouseEvent e) {
                System.out.println("Mouse Moved...");
            }
        });

        getContentPane().add(textArea);
    }
}