将鼠标事件分派给最深的可见JComponent

时间:2016-12-07 11:51:33

标签: java swing events jpanel jbutton

屏幕顶部有一个透明的JPanel,并添加了一个背景JPanel和一个JButton(所有内容都可见且有鼠标监听器)

在透明面板的侦听器中处理鼠标事件后,应将它们发送到下一个更深的组件(即后台面板或其按钮)

单击背景面板即可,但点击该按钮会导致不需要的ClassCastException

示例:

//making frame
frame=new JFrame();
frame.setVisible(true);

//making layered pane
layeredPane = new JLayeredPane();
frame.add(layeredPane);


//transparent panel on top
frontPanel = new JPanel();
frontPanel.setOpaque(false);
layeredPane.add(frontPanel,Integer.valueOf(1));

//background panel containing a button
backPanel = new JPanel();
JButton button = new JButton();
backPanel.add(button);
layeredPane.add(backPanel,Integer.valueOf(0));

//listeners
button.addMouseListener(new MouseListener()...a blank listener...);
backPanel.addMouseListener(new MouseListener()...a blank listener...);
frontPanel.addMouseListener(new MouseListener() {
    @Override
    public void mouseClicked(MouseEvent e) {
        SwingUtilities.getDeepestComponentAt(backPanel, e.getX(), e.getY()).dispatchEvent(e);
    }

    @Override
    public void mousePressed(MouseEvent e) {
        SwingUtilities.getDeepestComponentAt(backPanel, e.getX(), e.getY()).dispatchEvent(e);
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        SwingUtilities.getDeepestComponentAt(backPanel, e.getX(), e.getY()).dispatchEvent(e);
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }
});

//setting dimensions
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frontPanel.setSize(screenSize);
backPanel.setSize(screenSize);
frame.setSize(screenSize);
//now clicking on the button cause a ClassCastException: JPanel cannot be cast to javax.swing.AbstractButton. why?

1 个答案:

答案 0 :(得分:1)

您不能只发送旧事件。旧事件包含有关原始事件(即组件源)的信息。

您需要在调度之前创建一个新的MouseEvent

例如,请参阅How to Use Root Panes上的Swing教程中的GlassPaneDemo