Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTabbedPane customize tab look

I want to customize the look of the tabs in JTabbedPane.
I want to start from the simplest and plainest behavior: no borders, solid color.
The problem is that a non-plainess still remains: the tabs slight margin overlap.

enter image description here

You see that since the second tab is selected, it is "brought to the fore". This is achieved by a slight margin overlap. Is there a (non tricky) way to disable this behavior?

simple, testable (just fix imports) code:

public class TabbedPane_LookStudy extends JFrame{

public static void main(String [] args) throws UnsupportedLookAndFeelException {
    UIManager.setLookAndFeel(new NimbusLookAndFeel());
    new TabbedPane_LookStudy().setVisible(true);
}

public TabbedPane_LookStudy() {
    JTabbedPane tp = new JTabbedPane();
    tp.setUI(new MyTabbedPaneUI());
    add(tp);

    tp.addTab("first",new JPanel());
    tp.addTab("second", new JPanel());
    tp.addTab("third", new JPanel());

    setPreferredSize(new Dimension(180,100));
    pack();
}

public static class MyTabbedPaneUI extends javax.swing.plaf.basic.BasicTabbedPaneUI {

    @Override
    protected void paintTab(Graphics g, int tabPlacement, Rectangle[] rects, 
               int tabIndex, Rectangle iconRect, Rectangle textRect) {
        Color savedColor = g.getColor();
        g.setColor(Color.PINK);
        g.fillRect(rects[tabIndex].x, rects[tabIndex].y, 
               rects[tabIndex].width, rects[tabIndex].height);
        g.setColor(Color.BLUE);
        g.drawRect(rects[tabIndex].x, rects[tabIndex].y, 
               rects[tabIndex].width, rects[tabIndex].height);
        g.setColor(savedColor);
    }
 }

}

like image 472
AgostinoX Avatar asked Oct 22 '11 11:10

AgostinoX


People also ask

How do I add a tab to JTabbedPane?

To create a tabbed pane, instantiate JTabbedPane , create the components you wish it to display, and then add the components to the tabbed pane using the addTab method.

How do you switch tabs in JTabbedPane by clicking a button?

You should use the method JTabbedPane. setSelectedIndex(int index) with the index of the tab you want. Save this answer.

What is displayed by JTabbedPane?

A JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display both text and an image. The shape of a tab and the way in which the selected tab is displayed varies by Look and Feel.


1 Answers

Correct way would be to implement Custom Look & Feel only. But if you want to play with XxxTabbedPaneUI, then maybe this post can help you with that.

for Nimbus will be better to check aephyr code depot

like image 166
mKorbel Avatar answered Nov 16 '22 01:11

mKorbel