如何向JTabbedPane标签添加关闭按钮?

时间:2012-07-19 02:30:41

标签: java swing tabs jtabbedpane

我正在使用JTabbedPane,我需要在选项卡中添加一个关闭按钮来关闭当前的关闭按钮。

我一直在搜索,据我所知,我必须从JPanel扩展并添加关闭按钮,因为他们说here 但是,有没有办法添加延伸JTabbedPane的关闭按钮,或者有更简单的方法吗?

提前致谢,我非常感谢您的时间和帮助。

7 个答案:

答案 0 :(得分:43)

基本上,您需要为选项卡提供“渲染器”。有关详细信息,请查看JTabbedPane.setTabComponentAt(...)

基本思想是提供一个将在选项卡上布局的组件。

我通常会创建一个JPanel,我在其上添加一个JLabel(用于标题),并根据我想要显示的内容,使用某种控件作为关闭操作。

tabPane.addTab(title, tabBody);
int index = tabPane.indexOfTab(title);
JPanel pnlTab = new JPanel(new GridBagLayout());
pnlTab.setOpaque(false);
JLabel lblTitle = new JLabel(title);
JButton btnClose = new JButton("x");

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

pnlTab.add(lblTitle, gbc);

gbc.gridx++;
gbc.weightx = 0;
pnlTab.add(btnClose, gbc);

tabPane.setTabComponentAt(index, pnlTab);

btnClose.addActionListener(myCloseActionHandler);

现在在其他地方,我建立了动作处理程序......

public class MyCloseActionHandler implements ActionListener {

    public void actionPerformed(ActionEvent evt) {

        Component selected = tabPane.getSelectedComponent();
        if (selected != null) {

            tabPane.remove(selected);
            // It would probably be worthwhile getting the source
            // casting it back to a JButton and removing
            // the action handler reference ;)

        }

    }

}

现在,您可以轻松使用您喜欢的任何组件并将鼠标监听器连接到它并监控鼠标点击...

<强>更新

以上示例仅删除当前活动的标签,有几种方法可以解决此问题。

最好的做法是为行动提供一些方法来找到与...相关联的标签。

public class MyCloseActionHandler implements ActionListener {

    private String tabName;

    public MyCloseActionHandler(String tabName) {
        this.tabName = tabName;
    }

    public String getTabName() {
        return tabName;
    }

    public void actionPerformed(ActionEvent evt) {

        int index = tabPane.indexOfTab(getTabName());
        if (index >= 0) {

            tabPane.removeTabAt(index);
            // It would probably be worthwhile getting the source
            // casting it back to a JButton and removing
            // the action handler reference ;)

        }

    }

}   

这使用标签名称(与JTabbedPane#addTab一起使用)来查找并删除标签及其相关组件...

答案 1 :(得分:6)

我找到了一个标签示例(来自java网站),似乎是这样做的,至少在他们看来。 (虽然我以为,当我过去尝试它时,它也关闭了当前选中的选项卡,虽然它在运行他们的示例时工作正常,但我认为当我更新它以在标签式java记事本上工作时,它正在关闭当前选择的标签,但也许我做错了。

http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TabComponentsDemoProject/src/components/ButtonTabComponent.java

是的,我现在正在努力!这将适用于实际的选项卡,而不是当前选定的选项卡!

答案 2 :(得分:0)

希望你能得到你问题的答案。我想提供一个对我非常有用的链接。

JTabbedPane with a close button

以下是一些代码。

public static void createAndShowGUI()
{
    JFrame frame = new JFrame("Tabs");
    frame.setMinimumSize(new Dimension(500, 200));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTabbedPane tabbedPane = new JTabbedPane();

    JPanel panel = new JPanel();
    panel.setOpaque(false);
    tabbedPane.add(panel);
    tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(panel), getTitlePanel(tabbedPane, panel, "Tab1"));

    JPanel panel1 = new JPanel();
    panel1.setOpaque(false);
    tabbedPane.add(panel1);
    tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(panel1), getTitlePanel(tabbedPane, panel1, "Tab2"));

    JPanel panel2 = new JPanel();
    panel2.setOpaque(false);
    tabbedPane.add(panel2);
    tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(panel2), getTitlePanel(tabbedPane, panel2, "Tab3"));

    JPanel panel3 = new JPanel();
    panel3.setOpaque(false);
    tabbedPane.add(panel3);
    tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(panel3), getTitlePanel(tabbedPane, panel3, "Tab4"));

    frame.add(tabbedPane);

    // Display the window.
    frame.pack();
    frame.setVisible(true);
}

答案 3 :(得分:0)

我在oracle的代码中做了一些更改。

http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TabComponentsDemoProject/src/components/ButtonTabComponent.java

可以在选项卡中添加图标,以及关闭标签按钮。希望有所帮助。

public static void addTag(JTabbedPane tab, String title, Icon icon, int index){
     MouseListener close = new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            //your code to remove component
            //I use this way , because I use other methods of control than normal: tab.remove(int index);
        }

    };
    final ButtonClose buttonClose = new ButtonClose (title, icon, close );

    tab.setTabComponentAt(index, buttonClose);
    tab.validate();
    tab.setSelectedIndex(index);

}

公共类ButtonClose扩展了JPanel {

public ButtonClose(final String title, Icon icon, MouseListener e) {
    JLabel ic = new JLabel(icon);
    ic.setSize(icone.getIconWidth(), icone.getIconHeight());

    JLabel text= new JLabel(title);
    text.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));

    ButtonTab button = new ButtonTab();
    button.addMouseListener(e);
    button.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));

    JPanel p = new JPanel();
    p.setSize(getWidth() - icone.getIconWidth(), 15);
    p.add(text);
    p.add(button);

    add(ic);
    add(p);
}

private class ButtonTab extends JButton {

    public ButtonTab() {
        int size = 13;
        setPreferredSize(new Dimension(size, size));
        setToolTipText("Close");

        setUI(new BasicButtonUI());

        setFocusable(false);
        setBorderPainted(false);

        addMouseListener(listener);
        setRolloverEnabled(true);
    }

    @Override
    public void updateUI() {
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g.create();

        if (getModel().isPressed()) {
            g2.translate(1, 1);
        }
        g2.setStroke(new BasicStroke(2));
        g2.setColor(new Color(126, 118, 91));

        if (getModel().isRollover()) {
            g2.setColor(Color.WHITE);
        }

        int delta = 3;
        g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1);
        g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1);
        g2.dispose();
    }
}

private final MouseListener listener = new MouseAdapter() {
    @Override
    public void mouseEntered(MouseEvent e) {
        Component component = e.getComponent();
        if (component instanceof AbstractButton) {
            AbstractButton button = (AbstractButton) component;
            button.setContentAreaFilled(true);
            button.setBackground(new Color(215, 65, 35));
        }
    }

    @Override
    public void mouseExited(MouseEvent e) {
        Component component = e.getComponent();
        if (component instanceof AbstractButton) {
            AbstractButton button = (AbstractButton) component;
            button.setContentAreaFilled(false); //transparent
        }
    }
};

}

答案 4 :(得分:0)

查看Peter-Swing here。它有一个 JClosableTabbedPane 类,以及许多其他类。

下载jar文件时,您可以运行该文件,并提供所有类的示例。

答案 5 :(得分:0)

您可以使用名为“x”的JLabel并使用mouseListener

 private final JLabel l = new JLabel(); // this is the label for tabbedPane
 private final JLabel b = new JLabel("x");//Close Button
 if (closeable)
        {
            b.setToolTipText("Click to close");

            b.setOpaque(false);
            b.setBackground(Color.gray);

            b.addMouseListener(new MouseAdapter()
            {
                @Override
                public void mouseExited(MouseEvent e)
                {
                    b.setBorder(bordere);
                    b.setOpaque(false);
                }

                @Override
                public void mouseEntered(MouseEvent e)
                {
                    b.setBorder(borderl);
                }

                @Override
                public void mouseReleased(MouseEvent e)
                {
                    b.setOpaque(false);
                    b.repaint();

                    if (b.contains(e.getPoint()))
                    {
                        b.setBorder(borderl);

                        if (confirmTabClosing())
                        {
                            tab.remove(tabIndex());
                            if(tab.getTabCount() == 0)
                                spacialTabComponent.maximizeOrRestore.doClick();
                        }
                    }
                    else
                        b.setBorder(bordere);

                }

                @Override
                public void mousePressed(MouseEvent e)
                {
                    b.setOpaque(true);
                    b.repaint();
                }
            });

            b.setBorder(bordere);
            add(b, getLeftAlignedBothFilledGBC(1, 0, new Insets(0, 0, 0, 0), 0, 0));
        }



    }

答案 6 :(得分:0)

jbCloseButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int index = jtbMainTabbedPane.indexOfTabComponent(jbCloseButton);
                jtbMainTabbedPane.remove(index);
            }
});