Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Hover effects can be implemented in Java Swing by using a combination of mouse events and graphics rendering.

Here's an example:

  1. Create a custom component that extends JComponent.

  2. Override the paintComponent() method to customize the appearance of the component.

  3. Override the mouseEntered() and mouseExited() methods to implement the hover effect.

  4. Use the Graphics object's setColor() and fillRect() methods to change the background color of the component when the mouse is hovered over it.

  5. Invoke the repaint() method to update the appearance of the component.

Here's the code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class HoverComponent extends JComponent {

    private boolean isHovered;

    public HoverComponent() {

        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                isHovered = true;
                repaint();
            }

            @Override
            public void mouseExited(MouseEvent e) {
                isHovered = false;
                repaint();
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        if (isHovered) {
            g.setColor(Color.GREEN);
        } else {
            g.setColor(Color.WHITE);
        }

        g.fillRect(0, 0, getWidth(), getHeight());
    }
}

To use this component in your Swing application, simply add it to a container like this:

JPanel panel = new JPanel();
HoverComponent hover = new HoverComponent();
panel.add(hover);

This will create a panel with a HoverComponent that changes color when the mouse is hovered over it.