2

In this JTabbedPane screenshot

screenshot

I am using DnD of Netbeans, and I've been tinkering around it just to put spaces between the tabs. So far I still can't get what I want.

Is there a way to do it?

trashgod
  • 203,806
  • 29
  • 246
  • 1,045

1 Answers1

6

I'm not sure of another way, but I think you have to install your own customized TabbedPaneUI on your JTabbedPane.

Example:

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

public class JTabbedPaneWithSpaces implements Runnable
{
  public static void main(String[] args) throws Exception
  {
    SwingUtilities.invokeLater(new JTabbedPaneWithSpaces());
  }

  public void run()
  {
    JTabbedPane pane = new JTabbedPane();
    pane.setUI(new SpacedTabbedPaneUI());
    pane.addTab("One", new JPanel());
    pane.addTab("Two", new JPanel());
    pane.addTab("Threeeeeee", new JPanel());
    pane.addTab("Four", new JPanel());

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(pane);
    frame.setSize(500, 200);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }

  public class SpacedTabbedPaneUI extends BasicTabbedPaneUI
  {
    @Override
    protected LayoutManager createLayoutManager()
    {
      return new BasicTabbedPaneUI.TabbedPaneLayout()
      {
        @Override
        protected void calculateTabRects(int tabPlacement, int tabCount)
        {
          final int spacer = 20; // should be non-negative
          final int indent = 4;

          super.calculateTabRects(tabPlacement,tabCount);

          for (int i = 0; i < rects.length; i++)
          { 
            rects[i].x += i * spacer + indent;
          } 
        }
      };
    }
  }
}
splungebob
  • 5,357
  • 2
  • 22
  • 45
  • how can i input the code to my program? im using DnD of Netbeans, and im still a beginner. – user3882642 Jul 29 '14 at 18:15
  • The `run()` method above is just a driver to demonstrate the behavior. You would need to: (1) create a separate class called `SpacedTabbedPaneUI` (or whatever name you want), implemented the same way as shown in my example. Then in your existing code where the JTabbedPane is created, (2) add the line `pane.setUI(new SpacedTabbedPaneUI());`, as I did in the 2nd line of my run() method. Just substitute "pane" with the name of your JTabbedPane variable. – splungebob Jul 29 '14 at 19:18
  • oh tnx, that helped me alot, so by changing the value of spacer it will have larger spacing between tabs right? – user3882642 Jul 29 '14 at 20:08
  • Yes - the spacer is the amount to widen (or shorten) the gap between tabs. The indent is the offset for the first tab. – splungebob Jul 29 '14 at 20:17