Swing:鼠标悬停时显示/隐藏按钮

asy*_*ync 6 java events swing button listener

所以我想在一个按钮中添加一个按钮JPanel,但我希望它保持不可见/隐藏,除非鼠标指针悬停在它上面.此时,应使按钮可见,对点击作出反应等.当鼠标离开该区域时,应该再次隐藏它.

我尝试添加一个MouseListener到我的JButton并使用setVisible(),但当我隐藏按钮(setVisible(false)),然后监听器不再工作 - 应用程序的行为就好像按钮根本不存在.

实现此行为的正确方法是什么?

编辑:我正在使用绝对布局(setLayout(null)),我手动放置我的组件使用setBounds(x, y, width, height).

And*_*son 7

使用图标分别显示(着色)或隐藏(透明)按钮.

在此输入图像描述

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

class InvisiButton {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                int size = 30;
                JPanel gui = new JPanel(new GridLayout(4,10,4,4));
                for (int ii=0; ii<40; ii++) {
                    JButton b = new JButton();
                    b.setContentAreaFilled(false);
                    b.setIcon(new ImageIcon(
                        new BufferedImage(size,size,BufferedImage.TYPE_INT_RGB)));
                    b.setRolloverIcon(new ImageIcon(
                        new BufferedImage(size,size,BufferedImage.TYPE_INT_ARGB)));
                    b.setBorder(null);
                    gui.add(b);
                }

                JOptionPane.showMessageDialog(null, gui);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
        SwingUtilities.invokeLater(r);
    }
}
Run Code Online (Sandbox Code Playgroud)