Swing: GlassPane prevents mouse pointer from changing

我怕爱的太早我们不能终老 提交于 2019-12-05 19:33:10

Well. I figure out how to do it.

Although I spend more than 5 hours to understand all things behind, but the solution is very simple.

Just overwrite 'public boolean contains(int x, int y)' method of glass panel.

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);
}

Well. I have found a solution to the problem "place buttons next to the tabs". I don't use a glass pane any more, but place the buttons directly:

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

This works and solves my problem. It is a bit more complicated and involves doing layout by hand and listening to frame resize events, though.

Since I still would like to know how to accomplish this with a glass pane, I'm not accepting this answer. Maybe someone comes up with a solution for a glass pane.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!