How to add close button to a JTabbedPane Tab?

前端 未结 7 1972
温柔的废话
温柔的废话 2020-11-27 05:09

I\'m working in with a JTabbedPane, I need to add a close button in the tabs to close the current one.

I have been searching and as I understand I must extend from J

7条回答
  •  隐瞒了意图╮
    2020-11-27 05:33

    You can have a JLabel named "x" and use the mouseListener

     private final JLabel l = new JLabel(); // this is the label for tabbedPane
     private final JLabel b = new JLabel("x");//Close Button
     if (closeable)
            {
                b.setToolTipText("Click to close");
    
                b.setOpaque(false);
                b.setBackground(Color.gray);
    
                b.addMouseListener(new MouseAdapter()
                {
                    @Override
                    public void mouseExited(MouseEvent e)
                    {
                        b.setBorder(bordere);
                        b.setOpaque(false);
                    }
    
                    @Override
                    public void mouseEntered(MouseEvent e)
                    {
                        b.setBorder(borderl);
                    }
    
                    @Override
                    public void mouseReleased(MouseEvent e)
                    {
                        b.setOpaque(false);
                        b.repaint();
    
                        if (b.contains(e.getPoint()))
                        {
                            b.setBorder(borderl);
    
                            if (confirmTabClosing())
                            {
                                tab.remove(tabIndex());
                                if(tab.getTabCount() == 0)
                                    spacialTabComponent.maximizeOrRestore.doClick();
                            }
                        }
                        else
                            b.setBorder(bordere);
    
                    }
    
                    @Override
                    public void mousePressed(MouseEvent e)
                    {
                        b.setOpaque(true);
                        b.repaint();
                    }
                });
    
                b.setBorder(bordere);
                add(b, getLeftAlignedBothFilledGBC(1, 0, new Insets(0, 0, 0, 0), 0, 0));
            }
    
    
    
        }
    

提交回复
热议问题