Question

I am trying to create a JTabbedPane so that the final "tab" is actually a button that will open up a dialog box to add something to the tabbed pane. I tried looking around the source for JTabbedPane, but I can't find where the tab objects (the row of clickable "buttons" that when clicked change the currently visible component) actually are. There is a private list of Page objects (so they can't be accessed by child classes anyway) but they only contain the info about the tab and aren't the tab object themselves. My goal is to be able to add a button that comes after the tab list (horizontally).

I also tried using JTabbedPane.setTabComponentAt() to change the string of the final tab to a JButton with a component of null, but that still adds the tab component. If you click slightly to the right/left of the button in the tab, a blank tab will show because there's always padding around the component. Perhaps there's a way to get rid of this? But I suppose in some Look and Feels that have tabs like this: /---\ instead of this: |---| you could still click in the tab but not click the button.

Does anyone know how I can get what I'm looking for without writing my own version of JTabbedPane?

Thanks!

Was it helpful?

Solution

My goal is to be able to add a button that comes after the tab list (horizontally).

The proper solution is to write a custom UI, but that can be complicated and I'm not sure what code to change.

As a simple hack you can us a panel with an OverlayLayout to display the button at the top/right of the tabbed pane:

import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.*;

public class TabbedPaneWithComponent
{
    private static void createAndShowUI()
    {
        JPanel panel = new JPanel();
        panel.setLayout( new OverlayLayout(panel) );

        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.add("1", new JTextField("one"));
        tabbedPane.add("2", new JTextField("two"));
        tabbedPane.setAlignmentX(1.0f);
        tabbedPane.setAlignmentY(0.0f);

        JCheckBox checkBox = new JCheckBox("Check Me");
        checkBox.setOpaque( false );
        checkBox.setAlignmentX(1.0f);
        checkBox.setAlignmentY(0.0f);

        panel.add( checkBox );
        panel.add(tabbedPane);

        JFrame frame = new JFrame("TabbedPane With Component");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( panel );
        frame.setLocationByPlatform( true );
        frame.setSize(400, 100);
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

Works pretty good except when the width of the tabbed pane becomes too small and the button overlaps the tabs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top