0

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: https://i.stack.imgur.com/IKD4t.jpg
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

JoaoP
  • 21
  • 7
  • I don't understand, you mean you don't want to loose your tab? – nachokk Jan 03 '14 at 16:06
  • No, the point is to add the close button to the previously created tab and don't loose the title nor the panel (dc) already inserted! The actual point of the thing is to add the 3 components, title, close button and jpanel. – JoaoP Jan 03 '14 at 16:07

1 Answers1

2

Read the section from the Swing tutorial on How to Use Tabbed Panes for an example of how to use a close button.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • 1
    An example about close button is shown [here](http://stackoverflow.com/questions/19787146/aligning-icon-to-the-left-in-jtabbedpane-in-nimbus-look-and-feel/19788356#19788356). – dic19 Jan 03 '14 at 16:13