How to display a jPanel when I position the mouse over a certain region?

0
Hello, I would like to know how I can create a Java algorithm to display a certain Panel within my JFrame Form, so that the user positions the mouse cursor over a certain preprogrammed region, which will be a specific corner of Form JFrame!

    
asked by anonymous 07.03.2015 / 04:29

2 answers

1

Does this help you? Explanations in 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.

    
07.03.2015 / 05:03
0

This effect you are trying to achieve is easier to implement using JavaFx because in it you can use CSS on the front end. In CSS you just use the hover property which is super easy and you do not have to use Java code.

    
07.03.2015 / 13:46