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.
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.