Naming & selecting Tabs in JTabbedPanes

Can anyone help me with a tabbed pane question. I have a working swing interface with some basic events but I don't know how to call on one my tabbed panes by name. I have a menu and action listener picking up menu choices. I would like to select the relevant tab when the menu item is clicked.
Here is the code I use to add the tab to the user interface. The trouble is I don't know how to refer to the tab by name.
For you information the frame object user interface is called "UI"
// this listener listens to all the tabs from what I understand.
tabbedPane.addMouseListener(this);
tabbedPane.addTab("Main Menu",null, new MenuPanel(), "Main menu");
//mouse listeners
public void mouseClicked(MouseEvent e)
topTitle.setText("Mouse released");
//Here I want to select the tab//
......more listeners
Can anyone provide an explantion and or example of setting and using names/indexs for tabbed panes.
Each menu item has a setActionCommand if this helps.
thanks

Quick'n'dirty answer:
public void mouseClicked(MouseEvent e)
topTitle.setText("Mouse released");
int idx = tabbedPane.indexOfTab("Main Menu")
tabbedPane.setSelectedIndex(idx);
}

Similar Messages

  • Changing Colors of selected tab in JTabbedPane.

    Do someone has some code that can show how to
    change the color of the selected tab with JTabbedPane.
    I can change the other tabs colors with setBackground and setForeground, setBackgroundAt........ but it is the selected
    tab that will not change from the default grey color.
    thanks

    try this code, it works.
    public class TabBackgroundChange extends JFrame {
    private JTabbedPane tabPane = null;
    public static final Color selTabColor = Color.red;
    Color nonSelectedTabColor = null;
    public TabBackgroundChange() {
    try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    catch(Exception ex) {
    ex.printStackTrace();
    tabPane = new JTabbedPane();
    tabPane.add("One", new JPanel());
    tabPane.add("Two", new JPanel());
    tabPane.add("Three", new JPanel());
    this.getContentPane().add(tabPane);
    this.setSize(200, 200);
    this.setVisible(true);
    tabPane.addChangeListener(new TabChangeListener());
    tabPane.setSelectedIndex(1);
    tabPane.setSelectedIndex(0);
    public static void main(String[] args) {
    TabBackgroundChange tabBackgroundChange1 = new TabBackgroundChange();
    private class TabChangeListener implements ChangeListener {
    public void stateChanged(ChangeEvent ce) {
    int iSelTab = tabPane.getSelectedIndex();
    Color unSelectedBackground = tabPane.getBackgroundAt(iSelTab);
    for(int i=0; i<tabPane.getTabCount(); i++) {
    tabPane.setBackgroundAt(i, unSelectedBackground);
    tabPane.setBackgroundAt(iSelTab, Color.red);
    }

  • Stopping right click selecting tab in JTabbedPane

    Hello all,
    This may be a really simple thing + I'm probably being thick, but is there a way to prevent a right click changing the selected tab on a JTabbedPane.
    I tried consuming the MouseEvent, but that didn't seem to work. Couldn't find an answer anywhere else in the forums & couldn't see anything in the JavaDoc that looked as if it would help.
    Answers on a postcard please......
    RT

    You might be able to extend JTabbedPane and override setSelectedIndex().
    I had to do this to work around a focus issue I had.
      This class extends JTabbedPane to correct a problem where it doesn't
      request focus when clicked on.
    import java.awt.*;
    import javax.swing.*;
    public class MyJTabbedPane extends JTabbedPane {
      public void setSelectedIndex(int index) {
        Component comp = KeyboardFocusManager.
            getCurrentKeyboardFocusManager().getFocusOwner();
        //  if  no tabs are selected
        // -OR- the current focus owner is me
        // -OR- I request focus from another component and get it
        // then proceed with the tab switch
        boolean noTabSelected = getSelectedIndex()==-1;
        boolean hasFocus = requestFocus(false);
        boolean compIsMe = comp==this;
        if(noTabSelected || hasFocus || compIsMe) {
          super.setSelectedIndex(index);
    }

  • Why isn't the selected tab title bold in JTabbedPane? How can I make it be?

    The selected tab title of JTabbedPanel is not bold. Is there a simple way to set it to be bold when a tab is selected? Thanks in advance.

    1. Simply use the HTML code in it's text like '<html><b>NameOfThisTab</b></html>'.
    2. Extend the JTabbedPane and fine-tune the font it uses.

  • How to insure selected tabs are visible in JTabbedPane

    Hello all,
    How can you insure that the selected tab in a JTabbedPane is visible.
    Here is the code:
    import javax.swing.*;
    import java.awt.*;
    public class TabbedPaneTest extends JTabbedPane implements Runnable
    public TabbedPaneTest()
    super(JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT);
    } // end TabbedPaneTest constructor
    public void run ()
    for (int i = 1; i <= 10; i ++)
    try
    this.addTab(Integer.toString(i), createDefaultPanel (i));
    this.getModel().setSelectedIndex(i - 1);
    Thread.sleep(3000);
    } // end try block
    catch (Exception e)
    e.printStackTrace();
    } // end catch block
    } // end for loop
    } // end run method
    private JPanel createDefaultPanel (int index)
    JPanel defaultPanel = new JPanel ();
    defaultPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLoweredBevelBorder(), Integer.toString(index)));
    return defaultPanel;
    } // end createDefaultPanel method
    public static void main (String args [])
    JFrame frame = new JFrame ();
    TabbedPaneTest tpt = new TabbedPaneTest ();
    frame.getContentPane().add(tpt);
    frame.setSize(200, 200);
    Thread newThread = new Thread (tpt);
    newThread.start();
    frame.setVisible(true);
    } // end main method
    } // end TabbedPaneTest class
    I've crated a JTabbedPane with the tabLayoutPolicy set to JTabbedPane.SCROLL_TAB_LAYOUT.
    If I add enough tabs the scroll buttons appear but the newly adde tab is hidden behind them,
    even though I have set the selection index to the added tab. The content of the panel associated
    with the tab is visible but the tab itself is hidden.
    So the selected tab is hidden behind the scroll buttons.
    Any one know how to insure that if a tab is selected it is visible to the user.
    Thanks

    This is an interesting question so I tried it out. After some poking around to see how Swing does this for mouse clicking (try setting things up so that a tab is only partially visible and then click on the visable part - notice how the whole tab is scrolled into view) I found this:    /**
         * This inner class is marked "public" due to a compiler bug.
         * This class should be treated as a "protected" inner class.
         * Instantiate it only within subclasses of BasicTabbedPaneUI.
        public class TabSelectionHandler implements ChangeListener {
            public void stateChanged(ChangeEvent e) {
                JTabbedPane tabPane = (JTabbedPane)e.getSource();
                tabPane.revalidate();
                tabPane.repaint();
                if (tabPane.getTabLayoutPolicy() == JTabbedPane.SCROLL_TAB_LAYOUT) {
                    int index = tabPane.getSelectedIndex();
                    if (index < rects.length && index != -1) {
                        tabScroller.tabPanel.scrollRectToVisible(rects[index]);
        }Which is called when the selected tab changes. The member theScroller is a private inner class that handles the scrolling tabs. The call to scrollRectToVisible is executed for each of your new tabs. Sometimes when I stopped in the debugger and then continued things worked and your new tab scrolled into view.
    So I tried putting your code into a Runnable class and invoked it later:          final int newIndex = i;
              SwingUtilities.invokeLater (new Runnable ()  {
                   public void run ()  {
                        addTab(Integer.toString(newIndex), createDefaultPanel (newIndex));
                        getModel().setSelectedIndex(newIndex - 1);
              });But that did not work. That is as far as I got so far and I have to stop now. Perhaps this can inspire someone else to a solution.
    IL
    PS. I first tried Rammensee's solution and it did not work.
    Rammensee, you said you hoped you had it right - perhaps you are close.

  • JTabbedPane - BOLD selected tab title text.

    I want to BOLD the selected tab's title text while keeping the unselected tabs' title text in normal font. Anyone know how to achieve this effect?

    I think the simplest  way is to use JTabbedPane.setTabComponentAt, add your own labels, add a ChangeListener to the JTabbedPane and change the labels fonts when tab selection changes.

  • Updating a JTabbedPane's selected tab color dynamically

    Hi
    I have set the selected tab color for my JTabbedPane
    using:
    UIManager.put("TabbedPane.selected", Color.RED);Now I would like to change the color dynamically to green.
    However, just calling:
    UIManager.put("TabbedPane.selected", Color.GREEN);doesn't work.
    It seems that if the JTabbedPane is visible while I change the color through the UIManager, it has no effect.
    On the other hand, all the other JTabbedPanes in my application (which are not visible - in hidden dialogs), are effected.
    How can I effect ALL the JTabbedPanes in my application at the same time?

    Try to call
    SwingUtilities.updateComponentTreeUI(selectedPane);
    best regards
    Stas

  • Listening to changes in tab selection on the JTabbedPane

    How can I to listen to any new selection in another tab of the JTabbedPane?
    supposed that I want the program to do a certain action each time the user select another tab with the mouse - and an action which is accordingly to the new selected index (of the new selected tab)...

    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JTabbedPane.html#addChangeListener(javax.swing.event.ChangeListener)

  • JTabbedPane selected tab size

    Hello everybody;
    I've created a JTabbedPane with JLabel on each tab and i want that the selected one size be larger than the other tabs.
    The problem is that if I increase the size of the selected tab, all the others (inselected tabs) do so (they take the same size as the selected one) which is normal.
    My need is to change this default behavior in order to fix the inselected tab size and increase the selected one to appear bigger
    Thank you for your help

    Hello,
    - JDK 6
    - MetalLookAndFeel
    - JTabbedPane#getTabPlacement()==TOP
    - Selected tab "width" only grow
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SelectedTabSizeTest{
      private static void addTab(JTabbedPane t, String title, Component c) {
        t.addTab(title, c);
        JLabel label = new JLabel(title, SwingConstants.CENTER);
        t.setTabComponentAt(t.getTabCount()-1, label);
      public JComponent makeUI() {
        JTabbedPane t = new JTabbedPane() {
          private void initTabWidth() {
            int tabCount  = getTabCount();
            if(tabCount==0) return;
            int bigger   = 50;
            int tabWidth = 30;
            int si = getSelectedIndex();
            for(int i=0;i<tabCount;i++) {
              JLabel l = (JLabel)getTabComponentAt(i);
              if(l==null) continue;
              int w = tabWidth+(si==i?bigger:0);
              int h = l.getPreferredSize().height;
              l.setPreferredSize(new Dimension(w, h));
          @Override public synchronized void repaint() {
            initTabWidth();
            super.repaint();
        t.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        addTab(t, "JTree",      new JScrollPane(new JTree()));
        addTab(t, "JTextArea",  new JScrollPane(new JTextArea("aaaa")));
        addTab(t, "Preference", new JScrollPane(new JTree()));
        addTab(t, "Help",       new JScrollPane(new JTextArea("bbbbbb")));
        t.setPreferredSize(new Dimension(320, 200));
        return t;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new SelectedTabSizeTest().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

  • Focus-requests when switching tabs in JTabbedPane

    I have a tabbed pane with a JTextArea in each tab. I would like to switch focus to the corresponding area each time I select a tab or create a new one. A ChangeListener can detect tab selections and call requestFocusInWindow() on the newly chosen tab's text area.
    For some reason, the focus only switches sporadically. Sometimes the caret appears to stay, sometimes it only blinks once, and sometimes it never appears. My friend's workaround is to call requestFocusInWindow() again after the setSelectedIndex() calls, along with a Thread.sleep() delay between them. Oddly, in my test application the delay and extra focus-request call are only necessary when creating tabs automatically, rather than through a button or shortcut key.
    Does the problem lie in separate thread access on the same objects? I tried using "synchronized" to no avail, but EventQueue.invokeLater() on the focus request worked. Unfortunately, neither the delay nor invokeLater worked in all situations in my real-world application. Might this be a Swing bug, or have I missed something?
    Feel free to tinker with my test application:
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    /**Creates a tabbed pane with scrollable text areas in each tab.
    * Each time a tab is created or selected, the focus should switch to the
    * text area so that the cursor appears and the user can immediately type
    * in the area.
    public class FocusTest2 extends JFrame {
         private static JTabbedPane tabbedPane = null;
         private static JTextArea[] textAreas = new JTextArea[100];
         private static int textAreasIndex = 0;
         private static JButton newTabButton = null;
         /**Creates a FocusTest2 object and automatically creates several
          * tabs to demonstrate the focus switching.  A delay between creating
          * the new tab and switching focus to it is apparently necessary to
          * successfully switch the focus.  This delay does not seem to be
          * necessary when the user fires an action to create new tabs, though.
          * @param args
         public static void main(String[] args) {
              FocusTest2 focusTest = new FocusTest2();
              focusTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              focusTest.show();
              //Opens several tabs.
              for (int i = 0; i < 4; i++) {
                   try {
                        //adding the tab should automatically invoke setFocus()
                        //through the tabbed pane's ChangeListener, but for some
                        //reason the focus often doesn't switch or at least doesn't
                        //remain in the text area.  The workaround is to pause
                        //for a moment, then call setFocus() directly
                        addTabbedPaneTab();
                        //without this delay, the focus only switches sporadically to
                        //the text area
                        Thread.sleep(100);
                        setFocus();
                        //extra delay simply for the user to view the tab additions
                        Thread.sleep(1900);
                   } catch (InterruptedException e) {
         /**Adds a new tab, titling it according to the index of its text area.
          * Using "synchronized" here doesn't seem to solve the focus problem.
         public static void addTabbedPaneTab() {
              if (textAreasIndex < textAreas.length) { //ensure that array has room
                   textAreas[textAreasIndex] = new JTextArea();
                   //title text area with index number
                   tabbedPane.addTab(
                        textAreasIndex + "",
                        new JScrollPane(textAreas[textAreasIndex]));
                   tabbedPane.setSelectedIndex(textAreasIndex++);
         /**Constructs the tabbed pane interface.
         public FocusTest2() {
              setSize(300, 300);
              tabbedPane = new JTabbedPane();
              //Action to create new tabs
              Action newTabAction = new AbstractAction("New") {
                   public void actionPerformed(ActionEvent evt) {
                        addTabbedPaneTab();
              //in my real-world application, adding new tabs via a button successfully
              //shifted the focus, but doing so via the shortcut key did not;
              //both techniques work here, though
              newTabAction.putValue(
                   Action.ACCELERATOR_KEY,
                   KeyStroke.getKeyStroke("alt T"));
              newTabAction.putValue(Action.SHORT_DESCRIPTION, "New");
              newTabAction.putValue(Action.MNEMONIC_KEY, new Integer('T'));
              newTabButton = new JButton(newTabAction);
              Container container = getContentPane();
              container.add(tabbedPane, BorderLayout.CENTER);
              container.add(newTabButton, BorderLayout.SOUTH);
              //switch focus to the newly selected tab, including newly created ones
              tabbedPane.addChangeListener(new ChangeListener() {
                   public void stateChanged(ChangeEvent evt) {
                        //note that no delay is necessary for some reason
                        setFocus();
         /**Sets the focus onto the selected tab's text area.  The cursor should
          * blink so that the user can start typing immediately.  In tests without
          * the delay during the automatic tab creation in main(), the cursor
          * sometimes only blinked once in the text area.
         public static void setFocus() {
              if (tabbedPane == null) //make sure that the tabbed Pane is valid
                   return;
              int i = tabbedPane.getSelectedIndex();
              if (i < 0) //i returns -1 if nothing selected
                   return;
              int index = Integer.parseInt(tabbedPane.getTitleAt(i));
              textAreas[index].requestFocusInWindow();
    }

    Did you ever get everything figured out with this? I have a similar problem ... which I have working, but it seems like I had to use a bunch of hacks.
    I think the problem with the mouse clicks is because each event when you click the moues (mousePressed, mouseReleased, mouseClicked) causes the tab to switch, and also these methods are called twice for some reason - for a total of 8 events giving the tab the focus instead of your textarea.
    This works, but seems aweful hacky:
         class TabMouseListener extends MouseAdapter
              private boolean switched = false;
              public void mousePressed( MouseEvent e ) { checkPop( e ); }
              //public void mouseReleased( MouseEvent e ) { checkPop( e ); }
              //public void mouseClicked( MouseEvent e ) { checkPop( e ); }
              public void checkPop( MouseEvent e )
                   if( e.isPopupTrigger() )
                        mousex = e.getX();
                        mousey = e.getY();
                        int index = tabPane.indexAtLocation( mousex, mousey );
                        if( index == -1 ) return;
                        tabMenu.show( tabPane, mousex, mousey );
                   else {
                        if( !switched )
                             switched = true;
                             e.consume();
                             int index = tabPane.indexAtLocation( e.getX(), e.getY() );
                             if( index != -1 )
                                  tabPane.setSelectedIndex( index );
                                  TabFramePanel panel = (TabFramePanel)tabPane.getComponentAt( index );
                                  if( panel != null ) panel.getInputComponent().requestFocus();
                        else {
                             switched = false;
                             TabFramePanel panel = (TabFramePanel)tabPane.getSelectedComponent();
                             if( panel != null ) panel.getInputComponent().requestFocus();
         }Do you know of a better way yet?
    Adam

  • Setting the Font of Selected Tab in JTabbed Pane

    Hi,
    i have A JTabbedPane , I want to set the font of the selected tab to be bold. Can anyone please tell me how can i do that...
    waiting for reply ,
    Bye
    Sanjeev

    http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=%2BJTabbedPane+%2Btab+%2Bfont&col=javaforums

  • Each tab of JTabbedPane has different border color

    Is it possible for the content area of each tab in JTabbedPane to have a different border color? Selecting Tab1 highlights content area of the tabbed pane in yellow, selecting tab2 highlights it in red, etc...
    Thanks

    Thanks for the quick response splungebob. How would I get a reference to the Jpanel of a specific tab? In my case each tab will have a toolbar, so I tried setting the toolbar border yellow, but I still have the default jtabbedpane border color surrounding my yellow bordered toolbar. I would prefer to set the color on the jtabbedpane, so that way the Tab itself does not also have the border going underneath it. For instance, I don't want the border to continue underneath the "my tab" tab, as illustrated below:
       | my tab |
    |                                                  |
    |                                                  |
    ----------------------------------------------------Edited by: 816886 on Nov 30, 2010 7:53 AM

  • Setting the color on selected Tab

    Hi,
    I can't seem to figure out how to set the color on the
    selected tab in a JTabbedPane. I've added a
    ChangeListener but when I try to use it, it only
    changes the color after the tab has been selected.
    I want to change it while it is selected.
    How can I do this?

    Maybe this helps:
    http://www2.gol.com/users/tame/swing/examples/SwingExamples.html
    Kurta

  • Tab of JTabbedPane bug perhaps?

    I've noticed many instances of JTabbedPane not setting current selected
    tabs to a specified color. I find this kind of strange since it seems
    like it's the other way around on my Solaris as well as my HP-UX box.
    What I'm wondering is if this is a new bug that got introduced by an
    attempt to "fix" the original bug where the selected tab is not taking
    the new color? If so, what's the workaround to getting the unselected
    tabs to respect the new color that one wishes to invoke?
    I've tried a myriad of techniques to get this unselected tab color to
    change to the color I wished for it to be, but to my dismay it always
    stay a Color.darkGray color. I was successful in changing the background
    of the selected, but not the unselected tabs.
    I've used UIManager and my own customized LookAndFeel manipulator to
    get the other stuff to work, except for this annoying "bug" it seems.
    Please help..
    Thanks in advance..

    Well.. I've been doing that and nothing seems to budge..
    Not sure exactly why it seems like whatever is done whether
    it be through the custom L&F or through custom subclass of
    JTabbedPane that forcibly/manually alter the color properties,
    nothing happens.
    So, to me, it just feels like an internal JVM bug.

  • Javascript to put text of selected tab in a header element at top of page

    Create a simple html document a header and main div's.   tab menu, say three tabs, in the main div.  Want the header to display the text of the selected tab.
    Here is the example with default SpryTabbedPanels.js and SpryTabbedPanels.css.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <script src="SpryAssets/SpryTabbedPanels.js" type="text/javascript"></script>
    <link href="SpryAssets/SpryTabbedPanels.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    <div id="header">Content for  id "header" Goes Here :Want this to be the text of the selected tab.</div>
    <div id="main">
      <div id="TabbedPanels1" class="TabbedPanels">
        <ul class="TabbedPanelsTabGroup">
          <li class="TabbedPanelsTab" tabindex="0">Tab 1 text</li>
          <li class="TabbedPanelsTab" tabindex="0">Tab 2 text</li>
          <li class="TabbedPanelsTab" tabindex="0">Tab 3 text<br />
          </li>
        </ul>
        <div class="TabbedPanelsContentGroup">
          <div class="TabbedPanelsContent">Content 1</div>
          <div class="TabbedPanelsContent">Content 2</div>
          <div class="TabbedPanelsContent">Content 3</div>
        </div>
      </div>
      main content
    </div>
    <script type="text/javascript">
    <!--
    var TabbedPanels1 = new Spry.Widget.TabbedPanels("TabbedPanels1");
    //-->
    </script>
    </body>
    </html>
    Anyone have a javascript for this?

    Just to clarify:

Maybe you are looking for

  • Java Networking and policy file

    Two part question, First I writing a applet that is working with sockets, I've compared this and a delphi program and it seems that the delphi program is writing to and recieving from the socket at a faster rate (four second delay for the applet) the

  • Custom trim function

    Hi, public String myTrim(String str)    return str.replace(/^\s*|\s*$/g,""); }I got this custom trim function from web,and it is working fine. can anybody plz tell me how does the code str.replace(/^\s*|\s*$/g,"");trims the string.

  • Getting the record data.

    Hi All, Good Morning. I had same question before, but there I was not getting the record data. This is my internal table structure. KUNNR, VKORG, VTWEG, SPART, CRDATE, EFDATE, SPRICE, EPRICE, SQTY, EQTY. This internal table is the user selected recor

  • Using You Tube in Ipad

    How to delete history of Most reviewed videos in you tube

  • Stop telling me I am not connected to the internet when I am!!!

    Itunes keeps telling me that I am not connected to the interenet when I am. I have allowed in fire wall but this has made no difference