Swing:GlassPane可防止鼠标指针发生变化

nok*_*kul 3 java mouse swing pointers glasspane

我有一个带有一些标签的JTabbedPane,标签旁边还有很多未使用的额外空间.所以我正在尝试使用它并在那里放置一些按钮(就像在Eclipse中一样).我把按钮放在GlassPane上:

        JPanel glasspane = getPanelWithButtons();
        // panel with FlowLayout.RIGHT
        frame.setGlassPane(glasspane);
        glasspane.setOpaque(false);
        glasspane.setVisible(true);
Run Code Online (Sandbox Code Playgroud)

这是有效的,我仍然可以点击我的gui的其他元素(我发现的大多数搜索结果都是关于如何防止这种情况).到目前为止唯一的问题是当鼠标指针悬停在JSplitPane的条形图上时,鼠标指针不会更改为该双端水平箭头.我怎样才能恢复这种行为?

编辑

我发现没有显示玻璃窗格下任何组件的鼠标更改事件.这些组件会将鼠标光标更改为手形光标,变焦镜头等.这些鼠标指针更改都不会产生任何影响.我想这是因为在玻璃窗格中,需要对玻璃窗格进行鼠标指针更改,但我不想手动更改所有鼠标指针.

che*_*976 7

好.我弄清楚该怎么做.

虽然我花了5个多小时来理解背后的所有事情,但解决方案非常简单.

只需覆盖玻璃面板的'public boolean contains(int x,int y)'方法.

public static void main(String[] args)
{
    final JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setSize(800, 600);

    final JSplitPane panel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JPanel(), new JPanel());

    frame.getContentPane().add(panel, BorderLayout.CENTER);

    final JPanel glassPane = new JPanel(){
        @Override
        public boolean contains(int x, int y)
        {
            Component[] components = getComponents();
            for(int i = 0; i < components.length; i++)
            {
                Component component = components[i];
                Point containerPoint = SwingUtilities.convertPoint(
                    this,
                    x, y,
                    component);
                if(component.contains(containerPoint))
                {
                    return true;
                }
            }
            return false;
        }
    };
    glassPane.setOpaque(false);
    JButton button = new JButton("haha");
    button.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            System.out.println("haha");
        }
    });
    glassPane.add(button);
    glassPane.setBorder(BorderFactory.createLineBorder(Color.red));
    frame.setGlassPane(glassPane);

    //try to comment out this line to see the difference.
    glassPane.setVisible(true);

    frame.setVisible(true);
}
Run Code Online (Sandbox Code Playgroud)