Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: "Add Tab Button" for a JTabbedPane

Is it possible to add a button to a tabbed pane like in firefox.

enter image description here

The plus-button is what I want.

Thanks

like image 346
Martijn Courteaux Avatar asked Dec 28 '09 19:12

Martijn Courteaux


People also ask

How do I add a tab to JTabbedPane?

To create a tabbed pane, instantiate JTabbedPane , create the components you wish it to display, and then add the components to the tabbed pane using the addTab method.

How do you switch tabs in JTabbedPane by clicking a button?

You should use the method JTabbedPane. setSelectedIndex(int index) with the index of the tab you want. Save this answer.

How do I add a tab to a Jpanel?

Each tab has a name. To add a tab to the JTabbedPane , simply call addTab() . You'll need to specify the name of the tab as well as a component that supplies the tab's contents. Typically, it's a container holding other components.

Which method is used for adding components to a JTabbedPane?

Tabs/components are added to a TabbedPane object by using the addTab and insertTab methods.


2 Answers

I think you should be able to manage it by building your own JTabbedPaneUI and setting it on the JTabbedPane using setUI.

Your ComponentUI has methods to get a hold of the accessible children. If you specify a JButton and a JLabel then you may be in business.

I haven't attempted this myself though. This is "at your own risk" :)

like image 157
Carl Smotricz Avatar answered Oct 01 '22 00:10

Carl Smotricz


You can try this:

public static void main (String[] args) {
    JFrame parent = new JFrame ();

    final JTabbedPane pane = new JTabbedPane ();
    pane.addTab ("test", null);
    FlowLayout f = new FlowLayout (FlowLayout.CENTER, 5, 0);

    // Make a small JPanel with the layout and make it non-opaque
    JPanel pnlTab = new JPanel (f);
    pnlTab.setOpaque (false);
    // Create a JButton for adding the tabs
    JButton addTab = new JButton ("+");
    addTab.setOpaque (false); //
    addTab.setBorder (null);
    addTab.setContentAreaFilled (false);
    addTab.setFocusPainted (false);

    addTab.setFocusable (false);

    pnlTab.add (addTab);

    pane.setTabComponentAt (pane.getTabCount () - 1, pnlTab);

    ActionListener listener = new ActionListener () {
        @Override
        public void actionPerformed (ActionEvent e) {
            String title = "Tab " + String.valueOf (pane.getTabCount () - 1);
            pane.addTab (title, new JLabel (title));
        }
    };
    addTab.setFocusable (false);
    addTab.addActionListener (listener);
    pane.setVisible (true);

    parent.add (pane);
    parent.setSize (new Dimension (400, 200));
    parent.setVisible (true);
}

Screenshot

like image 30
user2287966 Avatar answered Oct 01 '22 00:10

user2287966