I'm trying to get a JTabbedPane
where all tabs (the actual tabs, not the components) have the same width (either the minimum width needed for the widest label or a constant width).
I've tried to override BasicTabbedPaneUI.getTabBounds(int tabIndex, Rectangle dest)
, but apparently this method isn't used by the painting methods of BasicTabbedPaneUI
, instead it uses a rects array to determine the tabs size.
My next approach would be to override JTabbedPane.insertTab(String title, Icon icon, Component component, String tip, int index)
and setting the preferred size of the label component, but this doesn't seem very elegant and I'm not even sure it would work at all.
Is there a way to achieve this?
The answer is simple.
When we put the name for the tab, just format the name using html.
say
tp - JTabbedPane object
tp.addTab("<html><body><table width='150'>Name</table></body></html>",Componentobject)
I think it's not as complicated as you've done. Just use setTabComponentAt() with a JLabel on which you've set preferred size.
I've tried the following:
tabPane.setUI(new javax.swing.plaf.metal.MetalTabbedPaneUI() {
@Override
protected int calculateTabHeight(int tabPlacement, int tabIndex, int fontHeight) {
return super.calculateTabHeight(tabPlacement, tabIndex, fontHeight) + 12;
}
});
This seems to work fine for me. But if your using a different L&F, you'll end up rendering it with the 'metal' regardless.
I guess you could get the default UI and do an 'instanceof' on it to determine which is being used and instantiate it accordingly.
For example:
TabbedPaneUI ui = tabPane.getUI();
if (ui instanceof WindowsTabbedPaneUI) {
// Create the windows rendition
} else if (ui instanceof MetalTabbedPaneUI) {
// Create the metal rendition
} else if (ui instanceof MotifTabbedPaneUI) {
// Create the motif rendition
} else if (ui instanceof SynthTabbedPaneUI) {
// Etc...
}
this is worked for me.
JLabel lab = new JLabel();
lab.setPreferredSize(new Dimension(200, 30));
jTabbedPane1.setTabComponentAt(0, lab); // tab index, jLabel
or try this change to all tab component in same sizes (called in main method)
UIManager.getLookAndFeelDefaults().put("TabbedPane:TabbedPaneTab.contentMargins", new Insets(10, 100, 0, 0));