0

I have a JTappedPane with a button on that I want to make close that tab. I am doing it like so:

jTabbedPane1.addTab(title, null, panel, null);

JPanel pnl = new JPanel();
    JButton close = new JButton();
    try {
        Image img = ImageIO.read(getClass().getResource("x.png"));
        close.setIcon(new ImageIcon(img));
      } catch (IOException ex) {
          ex.printStackTrace();
      }
    close.setPreferredSize(new Dimension(10, 10));
    close.setBorderPainted(false);
    close.addActionListener(new java.awt.event.ActionListener(){

        public void actionPerformed(ActionEvent evt) {
                    //TODO CLOSE THE TAP WHEN BUTTON IS PRESSED

                }

        }});
    JLabel lab = new JLabel(s);

     pnl.setOpaque(false);
     pnl.add(lab);
      pnl.add(close);

jTabbedPane1.setTabComponentAt(jTabbedPane1.getTabCount() - 1, pnl);

I am trying to get the title of the tab on the tab that the button has been pressed on. I thought i could do something like close.getContaining() to return the tab it is on but I was wrong.

Any Ideas?

Sagarmichael
  • 1,624
  • 7
  • 24
  • 53
  • Well the title is `title` why don't you just take this? – Kai Nov 28 '12 at 11:55
  • because title changes all the time and i don't want to keep an array or hashMap of title when I don't have to. Also the correct answer has now been given. – Sagarmichael Nov 28 '12 at 17:27

2 Answers2

2

If I understand you correctly, you want to find the index of the tab which has the parent of the button as tabComponent:

public void actionPerformed(ActionEvent evt) {
    JComponent source = (JComponent) evt.getSource();
    Container tabComponent = source.getParent();
    int tabIndex = jTabbedPane1.indexOfTabComponent(tabComponent);
    jTabbedPane1.removeTabAt(tabIndex);
}
kleopatra
  • 51,061
  • 28
  • 99
  • 211
0

You could simply write:

jTabbedPane1.removeTabAt(jTabbedPane1.getSelectedIndex());
Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117