I have 3 tabs in my JTabbedPane and I want to have them next to each other, like this:
However, I didn't find how to automaticly set the width of the JTabbedPane, so that the tabs would fit next to each other, so I just set the width by tabs.setPreferredSize(new Dimension(210, 300));
This has of course many problems, mainly it doesn't even work on all systems:
Not to mention problems with renaming or adding/removing tabs.
So, is there a good way to calcuate the width of the tab names, to then pass into the setPrefferedSize()
method, or better yet, some setWidthToFitTabs()
method?
EDIT: minimal complete example:
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Tabs text");
JTabbedPane tabs = new JTabbedPane();
tabs.addTab("Tab1", new JLabel("Content1"));
tabs.addTab("Tab2", new JLabel("Content2"));
tabs.addTab("Tab3", new JLabel("Content3"));
tabs.addTab("Tab4", new JLabel("Content4"));
for (int i = 0; i < tabs.getTabCount(); i++) {
System.out.println(tabs.getUI().getTabBounds(tabs, i));
}
frame.add(tabs);
frame.pack();
frame.setVisible(true);
});
Result:
java.awt.Rectangle[x=2,y=59,width=-8,height=19]
java.awt.Rectangle[x=2,y=40,width=-8,height=19]
java.awt.Rectangle[x=2,y=21,width=-8,height=19]
java.awt.Rectangle[x=2,y=2,width=49,height=19]