Domanda

I have a JTabbedPane object in my program and I override the getForegroundAt and getBackgroundAt methods in order to have different background colours when the tab is selected or not. I want to change the width and height of the tabs. I managed to do that using code similar as the following:

 jtp.addTab("<html><body><table width='200'>Main</table></body></html>", mainPanel);

The problem is that if I use this html code to change the width of the tabs, the methods which I override are not longer called because the options are set with the html code. Is there a way to work around this problem? Is there html code that I can use in order to change the background colour of the tab depending on whether it is selected or not? Thanks.

È stato utile?

Soluzione

Here's one way to change the width of the tabs by overriding calculateTabWidth(...) in the JTabbedPane's UI:

EDIT: MadProgrammer's comment is correct. I've changed the sample from BasicTabbedPaneUI to MetalTabbedPaneUI, since that's the default UI used for this sample. If you're specifiying a specific L&F for your app, then change the UI accordingly.

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

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

  public void run()
  {
    JTabbedPane tabbedPane = new JTabbedPane();
    tabbedPane.setUI(new MetalTabbedPaneUI()
    {
      @Override
      protected int calculateTabWidth(int tabPlacement, int tabIndex,
                                      FontMetrics metrics)
      {
        int width = super.calculateTabWidth(tabPlacement, tabIndex, metrics);
        int extra = tabIndex * 50;
        return width + extra;
      }
    });

    tabbedPane.addTab("JTable", new JScrollPane(new JTable(5,5)));
    tabbedPane.addTab("JTree", new JScrollPane(new JTree()));
    tabbedPane.addTab("JSplitPane", new JSplitPane());

    JPanel p = new JPanel();
    p.add(tabbedPane);

    JFrame frame = new JFrame();
    frame.setContentPane(p);
    frame.pack();
    frame.setVisible(true);
  }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top