JTabbedPane - MouseEvents on tabs

I'm trying to find some way to add MouseListeners to tabs on a JTabbedPane. I can easily add them, of course, to the components denoted by the tabs, but I need them listening for MouseEvents on the actual buttons that switch tabs themselves.
So far, the only method I can think of is adding the listener to the whole JTabbedPane. If the event isn't within the currently focused component, then it must be in one of the tabs, so I compare the tooltip for that point against the tooltip of the current tab, but this won't work properly if more than one tab has the same tooltip. Anyone have any better ideas?

And you're well advised to use only methods on TabbedPaneUI without casting it to BasicTabbedPaneUI or any other specific UI delegate since that can throw a ClassCastException when run under different core or third-party look-and-feel. By the way, those are not real buttons (unfortunately), so you'll have to add the mouse listener to the entire tabbed pane (like in the linked example).

Similar Messages

  • Jtabbedpane with replacing tab content

    Hello,
    I am developing an applet that should contain a JTabbedPane with 2 tabs.
    The second tab is easy to do because ti contains one Jpanel all the way.
    the first however is an issue, because i am supposed to change its content when the applet is running.
    this means i have 3 JPanels, J1, J2, J3.
    At tge beginning the applet contains J1 in the first tab.
    and J1 contains a button. when i click that button the applet should replace J1 with J2.
    the problem is i haven't managed to find a solution yet :(
    I have tried with setvisible(false) and validate(). It won't work. I also tried to add the J2 panel over J1, but encountered no succes.
    anybody has any idea ?
    Message was edited by:
    asrfel

    If you want to change back and forth repeatedly then wrap J1/2/3 in a JPanel with a CardLayout.
    If you can discard one when it's done with, use the remove() and insertTab() methods of JTabbedPane.

  • JTabbedPane with non-tabbed text

    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.'

    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)
                        super.paintComponent(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"));
              getContentPane().add(tabbedPane);
         public static void main(String args[])
            TabbedPaneWithText frame = new TabbedPaneWithText();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }

  • Bold in JTabbedPane title overlapping tab edge

    I extended the BasicTabbedPaneUI and implemented paintText() to use a bold font if the tab is selected. This works OK, unless the tab has a long title in which case the bold text overlaps the edge of the tab. I tried using a smaller font size, but it still didn't work in some cases.
    How do I change the size of the tab?
    Here's my implementation:
    -------------------------MyTabbedPane.java-----------------------
    <pre>
    import javax.swing.plaf.basic.BasicTabbedPaneUI;
    import java.awt.*;
    public class MyTabbedPaneUI extends BasicTabbedPaneUI {
         private Font boldFont = null;
         public MyTabbedPaneUI(Font font)
              this.boldFont = new Font(font.getFontName(), Font.BOLD, font.getSize());
         protected void paintText(Graphics g,
                                  int tabPlacement,
                                  Font font,
                                  FontMetrics metrics,
                                  int tabIndex,
                                  String title,
                                  Rectangle textRect,
                                  boolean isSelected)
              if(isSelected)
                   super.paintText(g, tabPlacement, boldFont, metrics, tabIndex, title, textRect, isSelected);
              else
                   super.paintText(g, tabPlacement, font, metrics, tabIndex, title, textRect, isSelected);
    </pre>
    ------Here's how it's used-----------
    JTabbedPane tabbedPaneTop = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.WRAP_TAB_LAYOUT);
    // set-up tab UI
    MyTabbedPaneUI tabUI = new MyTabbedPaneUI(tabbedPaneTop.getFont());
    tabbedPaneTop.setUI(tabUI);

    I figured out how to fix my problem. Had to override a couple more methods. See my code below.
    import javax.swing.plaf.basic.BasicTabbedPaneUI;
    import java.awt.*;
    import javax.swing.*;
    public class MyTabbedPaneUI extends BasicTabbedPaneUI {
         private Font boldFont = null;
         private FontMetrics boldFM = null;
         public MyTabbedPaneUI(Font font)
              this.boldFont = new Font(font.getFontName(), Font.BOLD, font.getSize());
         public void installUI(JComponent c)
              super.installUI(c);
              this.boldFM = c.getFontMetrics(this.boldFont);
         protected void paintText(Graphics g,
                       int tabPlacement,
                       Font font,
                       FontMetrics metrics,
                       int tabIndex,
                       String title,
                                  Rectangle textRect,
                       boolean isSelected)
              if(isSelected)
                   Rectangle rect = this.getTabBounds(this.tabPane, tabIndex);
                   int centerX = rect.x + rect.width/2;
                   int centerY = rect.y + rect.height/2;
                   int textH = this.boldFM.getHeight();
                   int textW = this.boldFM.stringWidth(this.tabPane.getTitleAt(tabIndex));
                   rect.x = centerX - textW/2;
                   rect.y = centerY - textH/2;
                   rect.width = textW;
                   rect.height = textH;
                   super.paintText(g, tabPlacement, boldFont, this.boldFM, tabIndex, title, rect, isSelected);
              else
                   super.paintText(g, tabPlacement, font, metrics, tabIndex, title, textRect, isSelected);
         protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics)
              if (this.tabPane.getSelectedIndex() == tabIndex)
                   return super.calculateTabWidth(tabPlacement, tabIndex, this.boldFM);
              else
                   return super.calculateTabWidth(tabPlacement, tabIndex, metrics);
    }

  • JFrame.pack() causes problems with jtabbedpane(making new tabs)and resizing

    I have a JFrame with a JTabbedPane inside of it. Inside of each tab I put a JPanel with a JTextArea in it. When I create a new tab, I do something like textArea.requestFocusInWindow();
    However, this will not work unless I do a frame.pack() right after I created the new tab and right before that line of code.
    This in turn causes another problem. If I resize the jframe and then create a new tab, the window will snap back to the size it had before creating the tab. I assume this has to do with the pack() function, however nothing else I try will make the cursor blink in the JTextArea.
    Is there a solution to this...either something to make the cursor blink or something other than the pack function to update the JFrame?
    Thank you

    This posting should help you out:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=581478

  • 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

  • JTabbedPane - vertical - which tab is selected?

    Using the Windows L&F, if you have the tabs in a JTabbedPane arranged horizontally it is clear and obvious which tab is selected. But with the tabs arranged vertically you've got to look very carefully to see which tab is selected, as there are rather fewer changes than for horizontal tabs.
    I can't be the first person whose users have complained about this - what's the conventional solution?
    (One thought is to make the background colour of the non-selected tabs "a bit darker"; I guess that would look OK but wouldn't mind a pointer as to how to do this in such a fashion that it will still work when the user changes the desktop colour scheme.)

    Using the Windows L&F, if you have the tabs in a JTabbedPane arranged horizontally it is clear and obvious which tab is selected. But with the tabs arranged vertically you've got to look very carefully to see which tab is selected, as there are rather fewer changes than for horizontal tabs.
    I can't be the first person whose users have complained about this - what's the conventional solution?
    (One thought is to make the background colour of the non-selected tabs "a bit darker"; I guess that would look OK but wouldn't mind a pointer as to how to do this in such a fashion that it will still work when the user changes the desktop colour scheme.)

  • JTabbedPane detect close tab event.

    How can I get a title of tab which user just close (in JTabbedPane)?? I tried ContainerListener and componentRemoved method, but I can't get appropriate String with title.
    Any ideas?

    One way is to use a change listener:
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTabbedPane;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    public class GetDeletedTab
      private static JTabbedPane tabbedPane = new JTabbedPane();
      private static String[] workDays =
        "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"
      private static int currentIndex = -1;
      private static int previousIndex = -1;
      private static void createAndShowUI()
        for (String day : workDays)
          tabbedPane.addTab(day, new JPanel());
        currentIndex = tabbedPane.getSelectedIndex();
        tabbedPane.addChangeListener(new ChangeListener()
          public void stateChanged(ChangeEvent e)
            int index = tabbedPane.getSelectedIndex();
            if (index != currentIndex)
              previousIndex = currentIndex;
              currentIndex = index;
              if (previousIndex != -1)
                String currTabTitle = tabbedPane.getTitleAt(currentIndex);
                String prevTabTitle = tabbedPane.getTitleAt(previousIndex);
                System.out.println("Previous Tab Title was: " + prevTabTitle );
                System.out.println("Current Tab Title is: " + currTabTitle);
                System.out.println();
        JFrame frame = new JFrame("GetDeletedTab");
        JPanel cPane = (JPanel)frame.getContentPane();
        cPane.setPreferredSize(new Dimension(600, 400));
        cPane.add(tabbedPane);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main(String[] args)
        java.awt.EventQueue.invokeLater(new Runnable()
          public void run()
            createAndShowUI();
    }

  • [JTabbedPane] get the tab index of a textfield

    Hello,
    I'm using a jTabbedPane to display data. On every tab I have several panels with JTextFields. I would like to know on wich index of the tabpane a textfield is located. So when a textfield is empty I can use tabpane.setSelectedIndex( i ) to set te focus to that tab.
    Enyone any tips?
    Greetings
    Hans

    I'm guessing that just setting focus on the text field doesn't cause the tab selection to change.
    So here's a brute force way to do it:
    a) find the parent container of the text field
    b) use the tabbedPane.getComponentAt(..) method to compare the above component. When they are equal you now which tab contains the text field.

  • JtabbedPane equally size tab width..

    Hello,
    I have a JTabbedPane with about 7 tabs, but the tab names are mostly short and the sum width of the tabs takes up about 80% of the TabbedPane.
    I'd like for the tab widths to take up the entire 100% of the tabbedPane (just a pref.) It would be nice if I could set the min tab width to 1/7 tabbedPane width. How can I set the width of each tab??

    this might start you off - needs lots of testing
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Testing extends JFrame
      JTabbedPane tp = new JTabbedPane();
      int tabPaneWidth;
      int tabCounter;
      public Testing()
        setLocation(300,100);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        for(int x = 0; x < 3; x++)
          JPanel p = new JPanel();
          p.setPreferredSize(new Dimension(600,400));
          tp.addTab(""+(++tabCounter),p);
        JButton btn = new JButton("Add Tab");
        JPanel p = new JPanel();
        p.add(btn);
        getContentPane().add(tp,BorderLayout.CENTER);
        getContentPane().add(p,BorderLayout.SOUTH);
        tabPaneWidth = tp.getPreferredSize().width;
        tp.setUI(new MyUI());
        setResizable(false);//otherwise needs a componentListener
        pack();
        btn.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            tp.addTab(""+(++tabCounter),new JPanel());}});
      class MyUI extends javax.swing.plaf.basic.BasicTabbedPaneUI
        protected int calculateTabWidth(int tabPlacement,int tabIndex, FontMetrics metrics)
          Insets margin = getInsets();
          return (int)((tabPaneWidth - margin.left - margin.right)/tp.getTabCount());
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • JTabbedPane - removing/adding tabs

    Using JDK 1.4, I am attempting to refresh a JTabbedPane based on a user selection. I have tried several approaches (removing all of the tabs from the JTabbedPane; removing the panel the JTabbedPane sits on from a larger panel). In both cases, doing a remove (JTabbedPane.removeAll for the JTabbedPane, and Panel.remove [component] for the panel), the area where the JTabbedPane should appear is blank. Here is the code I have tried (createTabs calls the addTab method; createTabPanel puts the tabbedpane on a panel):
    public void refreshWindow ( String asReportNo )
         // Remove current tab panel from main panel
         csjpMainPanel.remove ( csjpTabPanel );
         // Recreate tabs, then tab panel
         //csjtab.removeAll();
         //csjtab.revalidate();
         JTabbedPane lsjtab = createTabs ( asReportNo );
         csjtab = lsjtab;
         csjpTabPanel = createTabPanel();
         //csjtab.setVisible ( true );
         //csjpTabPanel.setVisible ( true );
         csjpTabPanel.revalidate();          
         csjpTabPanel.repaint();
         // Put tab panel back on main panel
         GridBagConstraints lgbc = new GridBagConstraints();
         lgbc.gridx = 1;
         lgbc.gridy = 0;
         lgbc.insets = new Insets ( 3, 3, 3, 3 );
         lgbc.weightx = 1.0;
         lgbc.weighty = 0.5;
         lgbc.fill = GridBagConstraints.BOTH;
         lgbc.anchor = GridBagConstraints.NORTHWEST;
         csjpMainPanel.add ( csjpTabPanel, lgbc );
         csjpMainPanel.repaint();          
    Any ideas on what I could do to make the tabbed pane visible? I saw that there was a problem with JTabbedPane in earlier releases, but this is with 1.4.
    Thanks,
    Van Williams

    yes, that's right... remove the synchronized blocks and replace them with invoke laters... If your are going to synchronize this, it has to be
    synchronized(monitor) {
    // update code
    -->
    synchronized(tabbedPane.getTreeLock()) {
    // update code
    which is still not as good as the following
    -->
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
      // update code
    };

  • JTabbedPane MouseListener on tabs

    I want to add a MouseListener to a JTabbedPane, but not on the content JPanel, but on the right of the tabs.
    (see this image: http://yfrog.com/aijtabbedpaneg , the arrows mark where I want the mouse to be clicked when the listener acts)
    How can I do this?
    A simple tabbedpane.addMouseListener doesn't work and I can't find the tabs component where I can add the listener.

    Here's my attempt.
    import java.awt.Dimension;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTabbedPane;
    import javax.swing.SwingUtilities;
    public class TabbedPaneTest {
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("Test");
                    frame.setBounds(20, 20, 300, 300);
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    JTabbedPane tabs = new JTabbedPane();
                    Dimension size = new Dimension(100, 200);
                    JLabel label = new JLabel("Label 1");
                    JLabel otherLabel = new JLabel("Label 2");
                    label.setPreferredSize(size);
                    otherLabel.setPreferredSize(size);
                    tabs.add("Tab 1", label);
                    tabs.add("Tab 2", otherLabel);
                    tabs.addMouseListener(new MouseAdapter() {
                        @Override
                        public void mouseClicked(MouseEvent e) {
                            JTabbedPane tabs = (JTabbedPane)e.getSource();
                            //Check that click was on tabbed pane itself an that there is no tab at that location.
                            System.out.println(tabs.findComponentAt(e.getX(), e.getY()) == tabs && tabs.indexAtLocation(e.getX(), e.getY()) == -1 ? "No tab at location." : "Tab at location.");
                    frame.add(tabs);
                    frame.setVisible(true);
    }

  • Urgent - How to add a new control instead of tabs in JTabbedPane

    Hi,
    Please give me an idea or a sample program for how to add a new control
    in JTabbedpane instead of tabs that means overlay any Java controls or pane
    in the tabpane empty place next to tabs

    "Urgent" is not relevant to the question. Your question is no more important than anybody elses.
    My answer in this posting show a limited solution:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=636289
    Otherwise I suggest you try using a layered pane approach:
    http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html

  • How can we prevent JTabbedPanes from transferring focus to components outside of the tabs during tab traversal?

    Hi,
    I noticed a strange focus traversal behavior of JTabbedPane.
    During tab traversal (when the user's intention is just to switch between tabs), the focus is transferred to a component outside of the tabs (if there is a component after/below the JTabbedPane component), if using Java 6. For example, if using the SSCCE below...
    import java.awt.BorderLayout;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class TabbedPaneTest extends JPanel {
        public TabbedPaneTest() {
            super(new BorderLayout());
            JTabbedPane tabbedPane = new JTabbedPane();
            tabbedPane.addTab("Tab 1", buildPanelWithChildComponents());
            tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
            tabbedPane.addTab("Tab 2", buildPanelWithChildComponents());
            tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
            tabbedPane.addTab("Tab 3", buildPanelWithChildComponents());
            tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
            tabbedPane.addTab("Tab 4", buildPanelWithChildComponents());
            tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(tabbedPane);
            JButton button = new JButton("Dummy component that gains focus when switching tabs");
            panel.add(button, BorderLayout.SOUTH);
             * To replicate the focus traversal issue, please follow these steps -
             * 1) Run this program in Java 6; and then
             * 2) Click on a child component inside any tab; and then
             * 3) Click on any other tab (or use the mnemonic keys ALT + 1 to ALT 4).
            button.addFocusListener(new FocusAdapter() {
                @Override
                public void focusGained(FocusEvent e) {
                    System.err.println("Gained focus (not supposed to when just switching tabs).");
            add(new JScrollPane(panel));
        private JPanel buildPanelWithChildComponents() {
            JPanel panel = new JPanel();
            BoxLayout boxlayout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
            panel.setLayout(boxlayout);
            panel.add(Box.createVerticalStrut(3));
            for (int i = 0; i < 4; i++) {
                panel.add(new JTextField(10));
                panel.add(Box.createVerticalStrut(3));
            return panel;
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("Test for Java 6");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TabbedPaneTest());
                    frame.pack();
                    frame.setVisible(true);
    ... Then we can replicate this behavior by following these steps:
    1) Run the program in Java 6; and then
    2) Click on a child component in any of the tabs; and then
    3) Click on any other tab (or use the mnemonic keys 'ALT + 1' to 'ALT + 4').
    At step 3 (upon selecting any other tab), the focus would go to the component below the JTabbedPane first (hence the printed message in the console), before actually going to the selected tab.
    This does not occur in Java 7, so I'm assuming it is a bug that is fixed. And I know that Oracle suggests that we should use Java 7 nowadays.
    The problem is: We need to stick to Java 6 for a certain application. So I'm looking for a way to fix this issue for all our JTabbedPane components while using Java 6.
    So, is there a way to prevent JTabbedPanes from passing the focus to components outside of the tabs during tab traversal (e.g. when users are just switching between tabs), in Java 6?
    Note: I've read the release notes between Java 6u45 to Java 7u15, but I was unable to find any changes related to the JTabbedPane component. So any pointers on this would be deeply appreciated.
    Regards,
    James

    Hi Kleopatra,
    Thanks for the reply.
    Please allow me to clarify first: Actually the problem is not that the child components (inside tabs) get focused before the selected tab. The problem is: the component outside of the tabs gets focused before the selected tab. For example, the JButton in the SSCCE posted above gets focused when users switch between tabs, despite the fact that the JButton is not a child component of the JTabbedPane.
    It is important for me to prevent this behavior because it causes a usability issue for forms with 'auto-scrolling' features.
    What I mean by 'auto-scrolling' here is: a feature where the form automatically scrolls down to show the current focused component (if the component is not already visible). This is a usability improvement for long forms with scroll bars (which saves the users' effort of manually scrolling down just to see the focused component).
    To see this feature in action, please run the SSCCE below, and keep pressing the 'Tab' key (the scroll pane will follow the focused component automatically):
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    import javax.swing.JViewport;
    import javax.swing.SwingUtilities;
    public class TabbedPaneAutoScrollTest extends JPanel {
        private AutoScrollFocusHandler autoScrollFocusHandler;
        public TabbedPaneAutoScrollTest() {
            super(new BorderLayout());
            autoScrollFocusHandler = new AutoScrollFocusHandler();
            JTabbedPane tabbedPane = new JTabbedPane();
            tabbedPane.addTab("Tab 1", buildPanelWithChildComponents(20));
            tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
            tabbedPane.addTab("Tab 2", buildPanelWithChildComponents(20));
            tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
            tabbedPane.addTab("Tab 3", buildPanelWithChildComponents(20));
            tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
            tabbedPane.addTab("Tab 4", buildPanelWithChildComponents(20));
            tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(tabbedPane);
            JButton button = new JButton("Dummy component that gains focus when switching tabs");
            panel.add(button, BorderLayout.SOUTH);
             * To replicate the focus traversal issue, please follow these steps -
             * 1) Run this program in Java 6; and then
             * 2) Click on a child component inside any tab; and then
             * 3) Click on any other tab (or use the mnemonic keys ALT + 1 to ALT 4).
            button.addFocusListener(new FocusAdapter() {
                @Override
                public void focusGained(FocusEvent e) {
                    System.err.println("Gained focus (not supposed to when just switching tabs).");
            button.addFocusListener(autoScrollFocusHandler);
            JScrollPane scrollPane = new JScrollPane(panel);
            add(scrollPane);
            autoScrollFocusHandler.setScrollPane(scrollPane);
        private JPanel buildPanelWithChildComponents(int numberOfChildComponents) {
            final JPanel panel = new JPanel(new GridBagLayout());
            final String labelPrefix = "Dummy Field ";
            final Insets labelInsets = new Insets(5, 5, 5, 5);
            final Insets textFieldInsets = new Insets(5, 0, 5, 0);
            final GridBagConstraints gridBagConstraints = new GridBagConstraints();
            JTextField textField;
            for (int i = 0; i < numberOfChildComponents; i++) {
                gridBagConstraints.insets = labelInsets;
                gridBagConstraints.gridx = 1;
                gridBagConstraints.gridy = i;
                panel.add(new JLabel(labelPrefix + (i + 1)), gridBagConstraints);
                gridBagConstraints.insets = textFieldInsets;
                gridBagConstraints.gridx = 2;
                textField = new JTextField(22);
                panel.add(textField, gridBagConstraints);
                textField.addFocusListener(autoScrollFocusHandler);
            return panel;
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("Test for Java 6 with auto-scrolling");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TabbedPaneAutoScrollTest());
                    frame.setSize(400, 300);
                    frame.setVisible(true);
    * Crude but simple example for auto-scrolling to focused components.
    * Note: We don't actually use FocusListeners for this feature,
    *       but this is short enough to demonstrate how it behaves.
    class AutoScrollFocusHandler extends FocusAdapter {
        private JViewport viewport;
        private JComponent view;
        public void setScrollPane(JScrollPane scrollPane) {
            viewport = scrollPane.getViewport();
            view = (JComponent) viewport.getView();
        @Override
        public void focusGained(FocusEvent event) {
            Component component = (Component) event.getSource();
            view.scrollRectToVisible(SwingUtilities.convertRectangle(component.getParent(),
                    component.getBounds(), view));
    Now, while the focus is still within the tab contents, try to switch to any other tab (e.g. by clicking on the tab headers, or by using the mnemonic keys 'ALT + 1' to 'ALT + 4')...
    ... then you'll notice the following usability issue:
    1) JRE 1.6 causes the focus to transfer to the JButton (which is outside of the tabs entirely) first; then
    2) In response to the JButton gaining focus, the 'auto-scrolling' feature scrolls down to the bottom of the form, to show the JButton. At this point, the tab headers are hidden from view since there are many child components; then
    3) JRE 1.6 transfers the focus to the tab contents; then
    4) The 'auto-scrolling' feature scrolls up to the selected tab's contents, but the tab header itself is still hidden from view (as a side effect of the behavior above); then
    5) Users are forced to manually scroll up to see the tab headers whenever they are just switching between tabs.
    In short, the tab headers will be hidden when users switch tabs, due to the Java 6 behavior posted above.
    That is why it is important for me to prevent the behavior in my first post above (so that it won't cause usability issues when we apply the 'auto-scrolling' feature to our forms).
    Best Regards,
    James

Maybe you are looking for

  • Error in using Quartz Schedular

    Hi All, I am using SOA 11.1.1.6,Jdev 11.1.1.6,WL 10.3.6 and OS is linux. I tried to implemented quartz schedular for invoking my bpel process for every 5 min. My bpel process receives 3 variable so i used the wsdl of my process while creating quartz

  • ABAP DUMP in ST03N : COMPUTE_BCD_OVERFLOW

    HI Guys,      When I go to ST03N, Expert Mode, Select the Daily workload, I double clicked on 15.03.2010, the system will hit the abap dump : COMPUTE_BCD_OVERFLOW. However, when I try for other dates, it is fine. Which meant it is only the 15.03.2010

  • Implementing slicers to apply 'OR' criteria instead of 'AND'

    In my dataset, there is one record per investment and separate fields for 'Funding Team', 'Managing Team' and 'Supporting Team'.  For a given investment these fields may or may not have the same value.  The pivot table I've created has one record per

  • Can I password protect a file I want to send in the pdf pack?

    I just subscribed to the pdf pack. I want to take pictures and send them as a protected file. How/can I do that with the subscription I just purchased?

  • Query regarding alignment of data in Application server

    My requirement is to download data to the application server. To get an aligned output, i need to give offset position manually for each input. For example :       lw_outtab+0(15) = in_itab-matnr.       lw_outtab+25(10) = in_itab-vkorg.           app