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.