How do I handle mouse event in Swing?

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 MouseListenerDemo extends JFrame {
    public MouseListenerDemo() {
        initComponents();
    }

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

    private void initComponents() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setTitle("Mouse Event Handling");
        setSize(500, 500);
        JTextArea textArea = new JTextArea();
        textArea.setText("Press the mouse button...");

        MouseAdapter mouseAdapter = new MyMouseAdapter();
        textArea.addMouseListener(mouseAdapter);
        getContentPane().add(textArea);
    }

    private static class MyMouseAdapter extends MouseAdapter {
        public void mouseClicked(MouseEvent e) {
            System.out.println("MouseListenerDemo.mouseClicked");
        }

        public void mousePressed(MouseEvent e) {
            System.out.println("MouseListenerDemo.mousePressed");
        }

        public void mouseReleased(MouseEvent e) {
            System.out.println("MouseListenerDemo.mouseReleased");
        }

        public void mouseEntered(MouseEvent e) {
            System.out.println("MouseListenerDemo.mouseEntered");
        }

        public void mouseExited(MouseEvent e) {
            System.out.println("MouseListenerDemo.mouseExited");
        }
    }
}

How do I get the system look and feel?

The UIManager.getSystemLookAndFeelClassName() method returns the current system LAF (Look and Feel) for Swing application. Do not forget to call the SwingUtilities.updateComponentTreeUI() method after setting the LAF to update the current application look and feel.

package org.kodejava.swing;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;

public class SystemLAFDemo {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setTitle("System LAF Demo");

        try {
            // Use the system look and feel for the swing application
            String className = UIManager.getSystemLookAndFeelClassName();
            System.out.println("className = " + className);
            UIManager.setLookAndFeel(className);
        } catch (Exception e) {
            e.printStackTrace();
        }

        SwingUtilities.updateComponentTreeUI(frame);
        frame.setVisible(true);
    }
}
System Look and Feel in Swing

System Look and Feel in Swing

How do I set the look and feel for Swing application?

package org.kodejava.swing;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import java.awt.FlowLayout;

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

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

    private void initComponents() {
        setSize(500, 500);
        setTitle("LAF Demo");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));

        JMenu menu = new JMenu("Look and Feel");

        // Get all the available look and feel that we are going to use for
        // creating the JMenuItem and assign the action listener to handle
        // the selection of menu item to change the look and feel.
        UIManager.LookAndFeelInfo[] lookAndFeels = UIManager.getInstalledLookAndFeels();
        for (UIManager.LookAndFeelInfo lookAndFeelInfo : lookAndFeels) {
            JMenuItem item = new JMenuItem(lookAndFeelInfo.getName());
            item.addActionListener(event -> {
                try {
                    // Set the look and feel for the frame and update the UI
                    // to use a new selected look and feel.
                    UIManager.setLookAndFeel(lookAndFeelInfo.getClassName());
                    SwingUtilities.updateComponentTreeUI(this);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            menu.add(item);
        }

        JMenuBar menuBar = new JMenuBar();
        menuBar.add(menu);

        getContentPane().add(menuBar);
        getContentPane().add(new JButton("Hello"));
    }
}
Java Swing Look and Feel (LAF)

Java Swing Look and Feel (LAF)

How do I get the available Swing look and feel?

The code snippet below describe how we can obtain the available look and feel in the current Swing platform. This information can then be made available to the user, so they can change to look and feel of the application in their preferences.

package org.kodejava.swing;

import javax.swing.UIManager;

public class AvailableLookAndFeel {
    public static void main(String[] args) {
        UIManager.LookAndFeelInfo[] lookAndFeels = UIManager.getInstalledLookAndFeels();

        for (UIManager.LookAndFeelInfo lookAndFeel : lookAndFeels) {
            // Get the name of the look and feel
            String name = lookAndFeel.getName();
            System.out.println("Name      = " + name);

            // Get the implementation class for the look and feel
            String className = lookAndFeel.getClassName();
            System.out.println("ClassName = " + className);
        }
    }
}

Below is the list of available look and feel produces by the code snippet above.

Name      = Metal
ClassName = javax.swing.plaf.metal.MetalLookAndFeel
Name      = Nimbus
ClassName = javax.swing.plaf.nimbus.NimbusLookAndFeel
Name      = CDE/Motif
ClassName = com.sun.java.swing.plaf.motif.MotifLookAndFeel
Name      = Windows
ClassName = com.sun.java.swing.plaf.windows.WindowsLookAndFeel
Name      = Windows Classic
ClassName = com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel

How do I format JTextField text to uppercase?

To change JTextField text to upper case can be easily done by adding a DocumentFilter to the JTextField component using the setDocumentFilter() method. The DocumentFilter allow us to filter action for changes in the document such as insert, replace and remove.

The code snippet below show us how to do it.

package org.kodejava.swing;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.HeadlessException;

public class DocumentFilterExample extends JFrame {
    public DocumentFilterExample() throws HeadlessException {
        initComponents();
    }

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

    protected void initComponents() {
        setSize(500, 500);
        setTitle("DocumentFilter Example");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));

        JTextField firstName = new JTextField();
        firstName.setPreferredSize(new Dimension(150, 20));
        JTextField lastName = new JTextField();
        lastName.setPreferredSize(new Dimension(150, 20));

        DocumentFilter filter = new UppercaseDocumentFilter();
        AbstractDocument firstNameDoc = (AbstractDocument) firstName.getDocument();
        firstNameDoc.setDocumentFilter(filter);

        AbstractDocument lastNameDoc = (AbstractDocument) lastName.getDocument();
        lastNameDoc.setDocumentFilter(filter);

        getContentPane().add(new JLabel("First Name: "));
        getContentPane().add(firstName);
        getContentPane().add(new JLabel("Last Name: "));
        getContentPane().add(lastName);
    }

    static class UppercaseDocumentFilter extends DocumentFilter {
        @Override
        public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr)
            throws BadLocationException {
            fb.insertString(offset, text.toUpperCase(), attr);
        }

        @Override
        public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
            throws BadLocationException {
            fb.replace(offset, length, text.toUpperCase(), attrs);
        }
    }
}
JTextField Uppercase Text

JTextField Uppercase Text