JTabbedPane - tab with close button reference

后端 未结 3 1631
青春惊慌失措
青春惊慌失措 2020-12-21 20:38

I want to build a tabbed interface in JAVA, with close button on each tab. For that I have used the following class: ButtonTabComponent

I have a button on my GUI whi

相关标签:
3条回答
  • 2020-12-21 21:14

    The error lies in the call

    pane.setTabComponentAt(PanelCounter, new ButtonTabComponent(pane, this));
    

    You don't want to add the button to the tab index PanelCounter but to the one just created. Its index can be obtained using getTabCount(), which of course at this point is one too high, hence:

    pane.setTabComponentAt(pane.getTabCount()-1, new ButtonTabComponent(pane, this));
    
    0 讨论(0)
  • 2020-12-21 21:36

    I was checking your code and I could accomplish using

    pane.remove(pane.getSelectedComponent());
    

    in the actionPerformed method.

    0 讨论(0)
  • 2020-12-21 21:36

    Here I am creating JTabbedPane tabs, with a close button for each tab. When the close button is clicked, only the respective tab closes.

    //This is where a tab is created in some other function of same class
    jtp.addTab("Create",new JPanel());  //jtp is a global JTabbedPane variable
    int index = jtp.indexOfTab("Create");
    jtp.setTabComponentAt(index,createTabHead("Create"));   
    
    public JPanel createTabHead(String title)
    {
        final String st=title;
        JPanel pnlTab = new JPanel();
        pnlTab.setLayout(new BoxLayout(pnlTab,BoxLayout.LINE_AXIS));
        pnlTab.setOpaque(false);
        JButton btnClose = new JButton("x");
        JLabel lblTitle = new JLabel(title+"    ");
        btnClose.setBorderPainted(false);
        btnClose.setOpaque(false);
    
        btnClose.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                 int i; 
                for(i=0;i<=jtp.getTabCount()-1;i++)//To find current index of tab
                {
                if(st.equals(jtp.getTitleAt(i)))
                        break;
                }                   
                   jtp.removeTabAt(i);
                 }
                });
    
         pnlTab.add(lblTitle);
        pnlTab.add(btnClose);
        return pnlTab;
    }
    
    0 讨论(0)
提交回复
热议问题