How do I display a jPanel when I place my mouse over a certain region?

Asked

Viewed 424 times

0

Hello, I would like to know how to create an algorithm in Java to display a certain Panel within my Form Jframe, as soon as the user positions the mouse cursor on a certain pre-programmed region, which will be a specific corner of the Form Jframe itself!

2 answers

1

Does this help you? Explanation in the code comments.

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * @author Victor
 */
public class MouseTest {
    public static void main(String[] args) {
        EventQueue.invokeLater(MouseTest::seguir);
    }

    private static void seguir() {
        // 1. Cria a JFrame.
        JFrame tela = new JFrame("Isto é uma tela");
        tela.setResizable(true);
        tela.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        // 2. Cria a JPanel que irá aparecer. Desenha algo dentro dele para ficar bem visível.
        JPanel panel = new JPanel() {
            @Override
            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setColor(Color.BLUE);
                g2.fillRect(0, 0, this.getWidth(), this.getHeight());
                g2.setColor(Color.YELLOW);
                char[] t = "Olá, eu sou o JPanel!".toCharArray();
                g2.drawChars(t, 0, t.length, 30, 10);
            }
        };
        panel.setPreferredSize(new Dimension(300, 30));
        tela.add(panel);
        panel.setVisible(false); // Inicialmente invisível.

        // 3. Faz com que ao passar o mouse perto do canto inferior direito da tela, a JPanel apareça.
        // O segredo é adionar um MouseMotionListener.
        Container content = tela.getContentPane();
        tela.addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {
                if (e.getX() > content.getWidth() * 0.9 && e.getY() > content.getHeight() * 0.9) panel.setVisible(true);
            }
        });

        // 4. Mostra a tela.
        tela.setMinimumSize(new Dimension(300, 300));
        tela.pack();
        tela.setVisible(true);
    }
}

Made with java 8.

0

This effect you seek to achieve is easier to implement using Javafx because in it you can use CSS at the front-end. No CSS just use the property hover which is super easy and you don’t have to use Java code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.