您应该处理JPanel
. 获取鼠标在 上的位置JPanel
,看看它是否在JButton
的范围内。
虽然大多数LayoutManager
s 忽略了不可见的组件,所以当按钮被隐藏时你不能总是得到它的边界——感谢 MadProgrammer。您应该添加一个附加组件来保留“位置”——例如使用 JPanel:
JPanel btnContainer = new JPanel(new BorderLayout()); // use BorderLayout to maximize its component
btnContainer.add(button); // make button the only component of it
panel.add(btnContainer); // panel is the JPanel you want to put everything on
panel.addMouseMotionListener(new MouseAdapter() {
public void mouseMoved (MouseEvent me) {
if (btnContainer.getBounds().contains(me.getPoint())) { // the bounds of btnContainer is the same as button to panel
button.setVisible(true); // if mouse position on JPanel is within the bounds of btnContainer, then make the button visible
} else {
button.setVisible(false);
}
}
});
button.addMouseLisener(new MouseAdapter() {
public void mouseExited (MouseEvent me) { // after thinking about it, I think mouseExited() is still needed on button -- because
// if you move your mouse off the button very quickly and move it out of panel's bounds,
// before panel captures any mouse move event, button will stay visible
button.setVisible(false); // And now, it will hide itself.
}
});
还有另一种“模拟”不可见按钮的方法。您可以覆盖类的paint()
方法,JButton
如果“不可见”清除一个空白矩形:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Demo extends JFrame {
class MyButton extends JButton {
private boolean show;
public MyButton (String text) { // You can implement other constructors like this.
super(text);
}
@Override
public void paint (Graphics g) {
if (show) {
super.paint(g);
} else {
g.setBackground(panel.getBackground());
g.clearRect(0, 0, getWidth(), getHeight());
}
}
public void setShow (boolean show) { // make a different name from setVisible(), use this method to "fakely" hide the button.
this.show = show;
repaint();
}
}
private MyButton btn = new MyButton("Yet another button");
private JPanel panel = new JPanel(new BorderLayout());
public Test () {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 500);
setLocationRelativeTo(null);
btn.setShow(false);
btn.setPreferredSize(new Dimension(100, 100));
btn.addMouseListener(new MouseAdapter() { // capture mouse enter and exit events of the button, simple!
public void mouseExited (MouseEvent me) {
btn.setShow(false);
}
public void mouseEntered (MouseEvent me) {
btn.setShow(true);
}
});
panel.add(btn, BorderLayout.NORTH);
add(panel);
setVisible(true);
}
}