---
title: "自定义Popup window."
author: "稻-草"
date: "2013-12-18T14:38:22Z"
tags: []
categories: ["编程语言"]
slug: "popup-window"
draft: false
lastmod: "2013-12-18T14:42:33Z"
id: 1991317
url: "https://dcao.iteye.com/blog/1991317"
---

基类：采用JFrame + setUndecorated(true);

 

```
import java.awt.Graphics;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class PopupWindow extends JFrame
{
    public PopupWindow()
    {
        setUndecorated(true);

        // setAlwaysOnTop(true);
        addWindowFocusListener(new WindowFocusListener()
        {
            public void windowGainedFocus(WindowEvent e)
            {

            }

            public void windowLostFocus(WindowEvent e)
            {
                SwingUtilities.invokeLater(new Runnable()
                {
                    public void run()
                    {
                        setVisible(false);
                        dispose();
                    }
                });
            }
        });

    }

    public void showPopup(int x, int y)
    {
        setLocation(x, y);
        setVisible(true);
        requestFocus();
    }

    @Override
    public void paint(Graphics g)
    {
        super.paint(g);
        g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
    }
}
```

 通过继承PopupWindow，就可以试下模拟弹出菜单。

唯一的缺点是没有阴影，看起来没有立体感。

 

效果图：

![](http://dl2.iteye.com/upload/attachment/0092/2612/0e6a6ef5-0614-3d95-b714-c06840626564.png)  
 

 这里有模拟阴影的方法， 还没试过：

[http://stackoverflow.com/questions/19105242/undecorated-jframe-shadow](http://stackoverflow.com/questions/19105242/undecorated-jframe-shadow)