1

In many apps, such as Google Chrome, tabs have an 'x' on the right side of their titles, which closes the tab when clicked. I Intend to make something like that in my Swing Application. I found this topic and tried to follow the advice. It seems however, that the method puts a button inside the tab, and not on its header. Here's my code:

private void addCloseBtn(String title){
    JPanel btnPane = new JPanel(new GridBagLayout());
    btnPane.setOpaque(false);
    btnPane.setSize(new Dimension(15, 15));

    JButton btn = new JButton("X");
    btn.setPreferredSize(new Dimension(12, 12));
    btn.setMargin(new Insets(0, 0, 0, 0));
    btn.setFont(new Font("Dialog", 1, 9));

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.weightx = 1;

    btnPane.add(btn, gbc);
    contentTabs.setComponentAt(contentTabs.indexOfTab(title), btn);
}

contentTabs is my frame's private classfield.

The btnPane covers whole tab, which is useless. What can I do to put it on the tab's header or at least in the upper right corner of the tab? And finally why btn.setSize() method does not work and btn.setPreferredSize() does?

Thanks in advance.

Community
  • 1
  • 1
Sventimir
  • 1,996
  • 3
  • 14
  • 25

1 Answers1

0

Thanks to share this topic! It help me very much.

I think you are wrong in this line:

btnPane.add(btn, gbc);

Before this you need to put the title in grid and then you can to put your button. Maybe you need to do this, like the code in the link you share with us:

btnPane.add("your title", gbc);

and after you increments the gbc properties:

gbc.gridx++; gbc.weightx = 0; and then this btnPane.add(btn, gbc);

Baoba
  • 1
  • 1