How do I get the JFrame of a component?

This code snippet gives an example on how to get the JFrame of a component. In this example we try to get the JFrame from a button action listener event. To get the JFrame we utilize the SwingUtilities.getRoot() method and this will return the root component of the component tree in out small program below which is a JFrame.

Beside getting the JFrame, in this program we also do small stuff like changing the frame background color by a random color every time a user presses the “Change Frame Color” button.

package org.kodejava.swing;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.HeadlessException;

public class GetFrameDemo extends JFrame {
    public GetFrameDemo() throws HeadlessException {
        initialize();
    }

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

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

        this.setLayout(new FlowLayout(FlowLayout.CENTER));

        final JLabel rLabel = new JLabel("r: ");
        final JLabel gLabel = new JLabel("g: ");
        final JLabel bLabel = new JLabel("b: ");

        JButton button = new JButton("Change Frame Background Color");
        button.addActionListener(e -> {
            Component component = (Component) e.getSource();

            // Returns the root component for the current component tree
            JFrame frame = (JFrame) SwingUtilities.getRoot(component);

            int r = (int) (Math.random() * 255);
            int g = (int) (Math.random() * 255);
            int b = (int) (Math.random() * 255);

            rLabel.setText("r: " + r);
            gLabel.setText("g: " + g);
            bLabel.setText("b: " + b);

            frame.getContentPane().setBackground(new Color(r, g, b));
        });

        this.getContentPane().add(button);
        this.getContentPane().add(rLabel);
        this.getContentPane().add(gLabel);
        this.getContentPane().add(bLabel);
    }
}
Get Swing Root Component

Get Swing Root Component

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);
    }
}

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