0

我有一个带有按钮的 JTappedPane,我想关闭该选项卡。我这样做是这样的:

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);

我正在尝试在已按下按钮的选项卡上获取选项卡的标题。我以为我可以做类似 close.getContaining() 的事情来返回它所在的选项卡,但我错了。

有任何想法吗?

4

2 回答 2

2

如果我理解正确,您希望找到将按钮的父级作为 tabComponent 的选项卡的索引:

public void actionPerformed(ActionEvent evt) {
    JComponent source = (JComponent) evt.getSource();
    Container tabComponent = source.getParent();
    int tabIndex = jTabbedPane1.indexOfTabComponent(tabComponent);
    jTabbedPane1.removeTabAt(tabIndex);
}
于 2012-11-28T12:33:27.023 回答
0

你可以简单地写:

jTabbedPane1.removeTabAt(jTabbedPane1.getSelectedIndex());
于 2012-11-28T11:57:14.153 回答