2009-06-07 29 views
0

这是一起问题提出在这里: JTabbedPane: Components before and after the tabs themselvesJTabbedPane的:将鼠标监听到标签,选择UI的部分不包含标签

我要附加一个鼠标监听器,允许拖动构建的谷歌铬状框架。首先,最初的拖动代码非常简单,可以直接使用this Kirill-post的鼠标拖动代码。我只想要这种行为,如果用户点击并拖动框架的“标题栏”,即标签(stick-uppers)所在的区域。这也很简单 - 只需将拖动代码更改为仅接受JTabbedPane上部区域(包含选项卡的部分)中的点击。

但是,我想进一步减少可抓取区域,并且只允许在没有被选项卡占据的区域中单击并拖动框架(stick-uppers - 任何人对此GUI元素有更好的名称?) - 再次与Chrome浏览器非常相似(Chrome浏览器在窗口模式下还在标签上方添加了一个栏,以便在许多标签处于活动状态时更容易地抓住框架,但Chrome完美无缺:可以在标签部分抓取窗口没有标签,甚至在小标签之间的标签!)

我真的想要做的,是能够将鼠标监听器附加到GUI的背景为标签 - 但如何完成这样的事情?

回答

1

查看this question(Swing中的可拖动选项卡)的解决方案后,我发现实际的TabbedPaneUI有一些方法可以解决这两个问题:只在选项卡区域拖动窗口,这是最难的部分,不在标签本身上方拖动。相关代码如下,在标有“// ::”的两部分中。该代码是从问题提及的Kirill代码改编而来的。代码不处理其他情况,而不是处理顶部的其他情况 - 这在考虑我想要做什么时很有意义。

 // mouse listener for dragging the host window 
     MouseAdapter adapter = new MouseAdapter() { 
      int lastX; 
      int lastY; 

      boolean _dragInitiated; 

      @Override 
      public void mousePressed(MouseEvent e) { 
       TabbedPaneUI ui = _windowTabs.getUI(); 

       // :: Won't drag if we're positioned above a tab in tab area 
       if (ui.tabForCoordinate(_windowTabs, e.getX(), e.getY()) != -1) { 
        _dragInitiated = false; 
        return; 
       } 

       // :: Won't drag if we're below the tab area 
       int maxY = 0; 
       for (int i = 0; i < _windowTabs.getTabCount(); i++) { 
        Rectangle bounds = ui.getTabBounds(_windowTabs, i); 
        int y = bounds.y + bounds.height; 
        if (y > maxY) { 
         maxY = y; 
        } 
       } 
       _dragInitiated = true; 
       if (maxY > 0) { 
        if (e.getY() > maxY) { 
         _dragInitiated = false; 
        } 
       } 

       Point eventLocationOnScreen = e.getLocationOnScreen(); 
       if (eventLocationOnScreen == null) { 
        Component source = (Component) e.getSource(); 
        eventLocationOnScreen = new Point(e.getX() + source.getLocationOnScreen().x, e.getY() 
          + source.getLocationOnScreen().y); 
       } 

       lastX = eventLocationOnScreen.x; 
       lastY = eventLocationOnScreen.y; 
      } 

      @Override 
      public void mouseDragged(MouseEvent e) { 
       if (!_dragInitiated) { 
        return; 
       } 

       Point eventLocationOnScreen = e.getLocationOnScreen(); 
       if (eventLocationOnScreen == null) { 
        Component source = (Component) e.getSource(); 
        eventLocationOnScreen = new Point(e.getX() + source.getLocationOnScreen().x, e.getY() 
          + source.getLocationOnScreen().y); 
       } 

       int dx = eventLocationOnScreen.x - lastX; 
       int dy = eventLocationOnScreen.y - lastY; 
       Window win = POTabbedFrame.this; 
       Point loc = win.getLocation(); 
       win.setLocation(loc.x + dx, loc.y + dy); 
       lastX = eventLocationOnScreen.x; 
       lastY = eventLocationOnScreen.y; 
      } 
     }; 
     _windowTabs.addMouseListener(adapter); 
     _windowTabs.addMouseMotionListener(adapter);