4、悬浮窗体的实现:
效果图
代码:
首先在main窗体中定义一个悬浮窗体变量,并实力化
private SuspendWindow suspendWindow;
this.suspendWindow=new SuspendWindow(this);
悬浮窗体实现:
private MainFrame mainFrame; // 鼠标在悬浮图标中的坐标 private int x; private int y; //右键菜单 private JPopupMenu popupMenu = new JPopupMenu(); private JMenuItem openItem=new JMenuItem("打开/关闭", ImageUtil.SUSPEND_OPEN_IMAGE); private JMenuItem addItem=new JMenuItem("新建下载任务", ImageUtil.SUSPEND_ADD_IMAGE); private JMenuItem removeItem=new JMenuItem("删除完成任务", ImageUtil.SUSPEND_REMOVE_IMAGE); private JMenuItem startItem=new JMenuItem("开始全部任务", ImageUtil.SUSPEND_START_IMAGE); private JMenuItem pauseItem=new JMenuItem("暂停全部任务", ImageUtil.SUSPEND_PAUSE_IMAGE); private JMenuItem quitItem=new JMenuItem("推出", ImageUtil.SUSPEND_QUIT_IMAGE); private BufferedImage img = ImageUtil .getImage(ImageUtil.SUSPEND_IMAGE_PATH); @Override public void paint(Graphics g) { // TODO Auto-generated method stub g.drawImage(img, 0, 0, this); } //创建右键菜单 private void createPopupMenu(){ //加入菜单 this.popupMenu.add(this.openItem); this.popupMenu .add(this.addItem); this.popupMenu .add(this.removeItem); this.popupMenu .add(this.startItem); this.popupMenu .add(this.pauseItem); this.popupMenu .add(this.quitItem ); } public SuspendWindow(MainFrame mainFrame) { // TODO Auto-generated constructor stub this.mainFrame = mainFrame; // 得到屏幕大小 Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); // 设置窗口大小 this.setSize(36, 36); // 设置窗口位置 int locationX = screen.width - screen.width / 5; int locationY = screen.height - (int) (screen.height / 1.06); this.setLocation(locationX, locationY); // 设置该窗口总是在前 this.setAlwaysOnTop(true); this.setVisible(true); initialListener(); createPopupMenu(); } public void initialListener() { this.addMouseMotionListener(new MouseMotionAdapter() { //实现悬浮窗口的拖动 public void mouseDragged(MouseEvent e) { // 获得当前鼠标在屏幕中的坐标 int xScreen = e.getXOnScreen(); int yScreen = e.getYOnScreen(); setLocation(xScreen - x, yScreen - y); } }); //实现悬浮窗口的拖动,当用户对窗口进行拖动的时候再对窗口的位置进行相应的改变。 this.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { x = e.getX(); y = e.getY(); } //当单击鼠标右键时显示菜单 public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { popupMenu.show(SuspendWindow.this, e.getX(), e.getY()); } } }); }
上面的代码参考网上资料