摇摆:在鼠标上显示/隐藏按钮 [英] Swing: Show/hide button on mouse over

查看:122
本文介绍了摇摆:在鼠标上显示/隐藏按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我想提出一个按钮在的JP​​anel ,但我想保持它的无形/隐藏,除非鼠标指针悬停它。此时,按钮应当可见的,反应的点击等。当鼠标离开的区域,应该再次隐藏

So I want to put a button in a JPanel, but I want to keep it invisible/hidden unless the mouse pointer hovers over it. At this point, the button should be made visible, react to clicks and so on. When the mouse leaves the area, it should be hidden again.

我尝试添加一个的MouseListener 我的的JButton ,并使用调用setVisible(),但是当我隐藏按钮(调用setVisible(假)),那么听者不工作了 - 该应用程序的行为如果按钮是不是如那里。

I tried adding a MouseListener to my JButton and use setVisible(), but when I hide the button (setVisible(false)), then the listener doesn't work anymore - the application behaves as if the button is not there at all.

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

What's the correct way to implement this behavior?

编辑:我使用的是绝对布局( setLayout的(空)),我手动将使用的setBounds我的组件(X,Y,宽,高)

I am using an absolute layout (setLayout(null)) and I am manually placing my component using setBounds(x, y, width, height).

推荐答案

使用图标以显示(彩色)或隐藏(透明)分别按钮。

Use icons to reveal (colored) or hide (transparent) the button respectively.

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);
    }
}

这篇关于摇摆:在鼠标上显示/隐藏按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆