How to set color of a tab in JTabbedPane container?

Many times we need to set the color of a tab in JTabbedPane, lets see how we can color the tab.

We can set different colors to every tab and its corresponding containers. JTabbedPane class provides two different methods setForegroundAt and setBackgroundAt , using which we can set both background and foreground colors of a tab.

Following program uses these methods to color the tab. Now lets see how these methods work.

1. setForegroundAt
setForegroundAt( int index, Color.color_name )

This method is used to set the foreground color of a tab inside JTabbedPane container. We can use two arguments, first is index which is the index of a tab which needs to be coloured. And second argument is the color which we need to set it as foreground color.
2. setbackgroundAt
setbackgroundAt( int index, Color.color_name )

This method is to set the background color of a tab. It also takes two arguments which are index and color. Index is the index of the tab which needs a background color and second argument is the color of background.

      JFrame tabbedFrame = new JFrame( "Tabbed Pane Example" );
      tabbedFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      JTabbedPane tabEx = new JTabbedPane();
      tabbedFrame.add( tabEx, BorderLayout.CENTER );
      JButton button = new JButton( "1st tab selected" );
      tabEx.add( "1st Tab", button );
      button = new JButton( "2nd tab selected" );
      tabEx.add( "2nd Tab", button );
      tabEx.setForegroundAt( 0, Color.RED ); // Setting foreground which is the color of text
      tabEx.setBackgroundAt(0, Color.GRAY ); // Setting background color
      tabEx.setForegroundAt( 1, Color.BLUE );
      tabEx.setBackgroundAt( 1, Color.GREEN );
      tabbedFrame.setSize( 300,200 );
      tabbedFrame.setVisible( true );

You can also check the post to set tooltip for a tab in JTabbedPane container
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment


Post a Comment