检查鼠标下的组件

时间:2016-10-11 15:00:48

标签: java swing

我在桌面Java项目中使用了SWING。

可以检查鼠标下的组件类型吗?

例如: 我有很多不同的组件,我想把鼠标放在上面,得到什么组件(例如JButton,ComboBox等)。有可能吗?

我不想为所有组件添加鼠标侦听器。也许有办法在整个面板上添加鼠标监听器......?

3 个答案:

答案 0 :(得分:2)

  

我不想将鼠标监听器添加到所有组件

您可以使用AWTEventListener侦听所有生成的事件。

查看Global Event Listeners以获取侦听MouseEvents和KeyEvents的示例。

答案 1 :(得分:1)

这个问题分为两部分。

<强> 1。获取鼠标事件

正如@carmickr所说,使用像Toolkit.getDefaultToolkit().addAWTEventListener(listener, eventMask)这样的AWTEventListener并使用事件掩码来过滤鼠标事件。

<强> 2。检查鼠标的组件

您需要获取GUI组件层次结构中的所有组件,并检查鼠标是否在每个组件内部。嵌套最深的是鼠标所在的位置。如果有所帮助,可以使用以下方法获取所有组件:

public static List<Component> getAllComponents(final Container c) {
    Component[] comps = c.getComponents();
    List<Component> compList = new ArrayList<Component>();
    for (Component comp : comps) {
        compList.add(comp);
        if (comp instanceof Container)
            compList.addAll(getAllComponents((Container) comp));
    }
    return compList;
}

遵循这两个步骤将确保您不会与可能正在使用的任何其他事件处理程序发生冲突。

答案 2 :(得分:1)

<强>解决

我使用事件-(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[self navigationController] setNavigationBarHidden:NO animated:YES]; [session startRunning]; NSInteger section = [self numberOfSectionsInCollectionView:self.collection_View] - 1; NSInteger item = [self collectionView:self.collection_View numberOfItemsInSection:section] - 1; NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:item inSection:section]; [collectionView scrollToItemAtIndexPath:lastIndexPath atScrollPosition:UICollectionViewScrollPositionBottom animated:YES]; } 和AWTEventListener作为@ Eric Bischoff说。

AWTEvent.MOUSE_EVENT_MASK

并且效果很好,使用 Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() { public void eventDispatched(AWTEvent e) { if (e.getSource() instanceof JButton) { JButton button = (JButton) e.getSource(); Log(button.getText()); } } }, AWTEvent.MOUSE_EVENT_MASK); 我获取活动的组件,检查它是否是JButton的实例,然后转换为JButton并且可以做很好的事情,例如actionPerformed on this button(do不要浪费时间点击e.getSource())。我这样做是为了优化我的应用程序,因为button.doClick()花费大约80~ms,但是当我们对来自此按钮的事件执行actionPerformed时,此成本为0ms(从委托到此按钮上的侦听器操作的时间)。