简体   繁体   中英

Close Button JTabbedPane

I am working with jtabbedpane and I am trying to set a close button to a tab but to not loose the title that it had!

Notes:

  • "GestorJanelas" is my JTabbedPane
  • The String "titulo" is the title of the tab
  • "dc" is the name of the jpanel that I add to the content of the tab

Here's my code:

if(nronda==(rondas.size()-2)){
                        String titulo = "MF"+node.toString();
                        GestorJanelas.addTab(titulo, dc);
                        GestorJanelas.setSelectedIndex(GestorJanelas.getTabCount()-1);
                        GestorJanelas.setTabComponentAt(GestorJanelas.getSelectedIndex(), new BtnFechar(GestorJanelas,titulo));
                    }else{

Steps:

  1. I add the tab to the jtabbedpane
  2. I set that tab to be the one selected as it was sent to be opened by the user
  3. I want to set an instance of "BtnFechar", (means CloseButton), to the tab but without loosing the title that I've already set previously.

Here's the code of my BtnFechar class:

public class BtnFechar extends JButton implements ActionListener {
JTabbedPane pane;
String titulo;
public BtnFechar(JTabbedPane p, String titulo) {
    this.pane = p;
    this.titulo = titulo;
    int size = 17;
    JLabel label = new JLabel();
    label.setText(titulo);
    add(label);
    setPreferredSize(new Dimension(size, size));
    setToolTipText("close this tab");
    //Make the button looks the same for all Laf's
    setUI(new BasicButtonUI());
    //Make it transparent
    setContentAreaFilled(false);
    //No need to be focusable
    setFocusable(false);
    setBorder(BorderFactory.createEtchedBorder());
    setBorderPainted(false);
    //Close the proper tab by clicking the button
    addActionListener(this);
}

@Override
public void actionPerformed(ActionEvent ae) {
    int i = pane.getSelectedIndex();
    if (i != -1) {
        pane.remove(i);
    }
}

Can anyone help me on this or tell me a way to insert the title on the tab?

This is what happens when the programm runs: http://imgur.com/DOnS6rH
Check the tab names, they disappear when i add a closebutton there!
Note: the tab currently selected has no button at all its just title and content

阅读Swing教程中有关如何使用选项卡式窗格的部分, 获取如何使用关闭按钮的示例。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM