【问题标题】:JTabbedPane: Attach mouse listener to the part of the tab-select UI that doesn't contain the tabsJTabbedPane:将鼠标侦听器附加到不包含选项卡的选项卡选择 UI 部分
【发布时间】:2009-06-07 16:50:53
【问题描述】:
这与此处提出的问题有关:
JTabbedPane: Components before and after the tabs themselves
我想附加一个鼠标监听器,允许拖动构建的类似谷歌浏览器的框架。开始,初始拖动代码相当简单,this Kirill-post 的鼠标拖动代码几乎可以直接使用。如果用户单击并拖动框架的“标题栏”,我只想要这种行为,即选项卡(标签)所在的区域。这也很简单 - 只需将拖动代码更改为仅接受 JTabbedPane 上部区域(包含选项卡的部分)的点击。
但是,我想进一步减少可抓取区域,并且只允许在不被选项卡占据的区域中单击并拖动框架(棒子 - 任何人有这个 GUI 元素的更好名称吗?) -再次很像 Google Chrome(Chrome 还在窗口模式下的选项卡上方添加了一个栏,如果许多选项卡处于活动状态,则更容易抓住框架。但是 Chrome 做到了完美:可以在选项卡部分中抓取窗口没有标签,甚至在标签之间的小 v 中!)
我实际上想要做的是能够将鼠标侦听器附加到选项卡的 GUI 背景 - 但是如何完成这样的事情呢?
【问题讨论】:
标签:
google-chrome
jtabbedpane
【解决方案1】:
看了this question(Swing中的可拖动标签)的解决方案后,我发现实际的TabbedPaneUI有一些方法可以解决这两个问题:只在标签区域拖动窗口,原来是最难的部分,并且在选项卡本身上方时不要拖动。相关代码如下,在标有“// ::”的两个部分中。该代码改编自问题提到的基里尔代码。除了选项卡位于顶部时,代码不处理其他情况 - 在考虑我想要做什么时这是有道理的。
// 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);