Swing:GlassPane会阻止鼠标指针的更改

5

我有一个带有一些选项卡和许多未使用的额外空间的JTabbedPane。因此,我尝试使用它并在选项卡旁边放置一些按钮(就像在Eclipse中一样)。我将按钮放在GlassPane上:

        JPanel glasspane = getPanelWithButtons();
        // panel with FlowLayout.RIGHT
        frame.setGlassPane(glasspane);
        glasspane.setOpaque(false);
        glasspane.setVisible(true);

这个方法是有效的,而且我仍然可以点击我的GUI上的其他元素(大多数搜索结果都是关于如何防止这种情况)。到目前为止唯一的问题是,当鼠标悬停在JSplitPane的条上时,鼠标指针不会变成双端水平箭头。我该如何恢复这种行为?

编辑

我发现玻璃板下的任何组件都没有鼠标更改事件显示。这些组件会将鼠标光标更改为手型光标、缩放镜头和其他光标。这些鼠标指针的更改都没有任何效果了。我想这是因为在玻璃板中,鼠标指针更改需要在玻璃板上进行,但我不想手动更改所有的鼠标指针。

2个回答

8

好的,我已经想出如何做了。

虽然我花费了超过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);
}

0

好的。我已经找到了解决“将按钮放在选项卡旁边”的问题的方法。我不再使用玻璃窗格,而是直接放置按钮:

buttonpanel.setBounds(...);
frame.getLayeredPane().add(buttonpanel, 1);

这个方法可行并解决了我的问题。不过,它有点复杂,需要手动布局并监听框架调整大小事件。

虽然如此,由于我仍然想知道如何使用玻璃窗格完成这个任务,所以我不接受这个答案。也许有人能提出一个玻璃窗格的解决方案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接