Forum Stats

  • 3,750,843 Users
  • 2,250,260 Discussions


JTabbedPane with non-tabbed text

843804 Member Posts: 45,751
edited Mar 12, 2005 12:32AM in Swing
OK, I'm stuck (again)

What I would like to do is have a tabbed pane (2 tabs) and then put some text (maybe in a JLable) on the same line as the tabs. I'll try to draw a picture for clearity. Anyone have any ideas about how to do this?

 ______    ______
/ tab1 \ /tab2  \         Here is some text
|    This is what changes                             |
|            when you switch tabs                     |
|                                                                        |
I think you can get the idea from that 'picture.'


  • camickr
    camickr Member Posts: 24,931
    The correct way is probably to override the TabbedPaneUI, but that too complicated for me, so here's a quick hack that might give you some ideas:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.plaf.*;
    public class TabbedPaneWithText extends JFrame
    	public TabbedPaneWithText()
    		JTabbedPane tabbedPane = new JTabbedPane()
    			public void paintComponent(Graphics g)
    				Rectangle lastTab = getUI().getTabBounds(this, getTabCount() - 1);
    				int tabEnd = lastTab.x + lastTab.width;
    				String text = "Some Text";
    				FontMetrics fm = getFontMetrics( getFont() );
    				int stringWidth = fm.stringWidth( text ) + 10;
    				int x = getSize().width - stringWidth;
    				if (x < tabEnd)
    					x = tabEnd;
    				g.drawString(text, x + 5, 18);
    		tabbedPane.add("1", new JTextField("one"));
    		tabbedPane.add("2", new JTextField("two"));
    	public static void main(String args[])
            TabbedPaneWithText frame = new TabbedPaneWithText();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.setLocationRelativeTo( null );
  • 843804
    843804 Member Posts: 45,751
    Thank you, what you posted got me on the right track.

    Thanks again!

  • 843804
    843804 Member Posts: 45,751
    The usual solution to this kind of problem is to use a renderer or editor.
    camickr has posted a paintComponent method that acts like a tabbed pane renderer, which renders text.

    The problem is that you can't add a component to more than one container, so if you have a JPanel you can only put it in one tab. When the user changes tabs, you can remove the component and add it to the next tab. If you use this approach, make sure to use invokeLater() to do the adding/removing of the tab's component.

    Or you can override paintComponent and render the tab. This works fine unless you want to edit the text, then you'll need a tabbed pane editor. So basically each tab would contain a tabbed pane editor, and the editor displays a shared JPanel that has text you can edit.
This discussion has been closed.