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();
}

Similar Messages

  • JTabbedPane: Exception occurred during event dispatching:

    Hi,
    I have a JTabbedPane where the tabs can be added dynamically by the method:
    private void addNewTab(JTable aTable) throws java.lang.NullPointerException
    final JTable t = aTable;
    Thread addTab = new Thread()
    public void run()
    JScrollPane scroller = new JScrollPane();
    JTable table;
    if (t==null)
    table = new JTable(columns, 0);
    else
    table = t;
    table.setColumnsEditable(colEditable);
    cachedTables.addElement(table);
    scroller.getViewport().setView(table);
    jtp.insertTab("Tab " + cachedTables.size(), null, scroller, "Tab", cachedTables.size()-1);
    jtp.updateUI();
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    jtp.setSelectedIndex(cachedTables.size()-1);
    jtp.validate();
    addTab.start();
    The problem is that occasionally (20% of the times) I receive this exception:
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         at javax.swing.plaf.basic.BasicTabbedPaneUI.rotateInsets(BasicTabbedPaneUI.java:1159)
         at javax.swing.plaf.basic.BasicTabbedPaneUI.getTabAreaInsets(BasicTabbedPaneUI.java:951)
         at javax.swing.plaf.basic.BasicTabbedPaneUI.calculateTabAreaHeight(BasicTabbedPaneUI.java:924)
         at javax.swing.plaf.basic.BasicTabbedPaneUI.paintContentBorder(BasicTabbedPaneUI.java:637)
         at javax.swing.plaf.basic.BasicTabbedPaneUI.paint(BasicTabbedPaneUI.java:358)
         at javax.swing.plaf.ComponentUI.update(ComponentUI.java:39)
         at javax.swing.JComponent.paintComponent(JComponent.java:395)
         at javax.swing.JComponent.paint(JComponent.java:687)
         at javax.swing.JComponent.paintChildren(JComponent.java:498)
         at javax.swing.JComponent.paint(JComponent.java:696)
         at javax.swing.JComponent.paintWithBuffer(JComponent.java:3878)
         at javax.swing.JComponent._paintImmediately(JComponent.java:3821)
         at javax.swing.JComponent.paintImmediately(JComponent.java:3672)
         at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:370)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:124)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:154)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:337)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:131)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:98)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:85)
    Does none know, how I can solve the problem?
    Thanks,
    Diego.

    Fix the NullPointerException. The stack trace tells you the line that caused the problem.

  • Detecting the TAB key

    With a recent release of Java, a KeyListener no longer detects the TAB key, which is now apparently considered to be a focus event, not a keyboard event. It is critical to our application, a terminal emulator, that we be able to detect TAB and SHIFT-TAB. I read somewhere about a work-around involving a FocusListener, but a FocusListener does not report when the TAB key is pressed. Can somebody help me here?

    I seem to have solved the problem, and I'd like to present my solution in case anybody else runs across the problem.
    We use an AWTEventlistener. This is intended to watch AWT events but not handle them. However, there is no reason why we shouldn't process tab events within it. AWT will continue to process the tab key as a focus switch, but this solution enabled us to get our applet working again. I hope that future releases of Java will pay more attention to backward compatibility however, so that this kind of fix is not needed.
    In the canvas class:
    // Add the event listener provided we are on a version of the VM
    // that supports it.
    try {
    if (Class.forName("java.awt.event.AWTEventListener")!= null) {
         Toolkit.getDefaultToolkit().addAWTEventListener(new Myeventlistener(), AWTEvent.KEY_EVENT_MASK);
    } catch (Throwable e) {}
    import java.awt.*;
    import java.awt.event.*;
    public class Myeventlistener implements AWTEventListener
    public void eventDispatched(AWTEvent e)
    KeyEvent k = (KeyEvent) e;
    if (k.getID() == k.KEY_PRESSED) {
    if (k.getKeyCode() == 9) {
    if (k.isShiftDown())
    // Process as BackTab Key
    else
    // Process as tab Key

  • 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).

  • Dynamic Tab UI Shell - close tab action & number of open tabs control

    Hi,
    I browsed through the forum, but could not get hold of any concrete solution for the question on how to capture the close tab action event and perform some action on that?
    The below thread discusses my question but does not appear to have a proper solution
    Re: Dynamic Tab UI Shell: controlling the Close icon
    And one other question is, currently in the TabContext the number of open tabs is set to 15 limit. How can I override that such that I do not allow more than 7 tabs open at a time?
    Please help me with the above two queries. Thanks !
    Regards,
    SS

    Sorry for so much delay. Finally, got some time to play with the template and downloading the dynamicTabTemplate source code and overriding the closeIcon worked like a charm.
    Let me summarize what I did to help someone who is looking for this :)
    1) Downloaded the source code for dynamicTabTemplate
    2) Added and additional attribute closeTab to the template
    +<attribute>+
    +<attribute-name>closeTab</attribute-name>+
    +<attribute-class>java.lang.String</attribute-class>+
    +<required>+
    true
    +</required>+
    +</attribute>+
    2) edited the dynamicTabShell.jspx, closeIcon commanlink actionListener to be bound to "#{viewScope.tabContext.closeIcon}"
    3) Implemented the closeIcon method in TabContext
    +@Override+
    +public void closeIcon(ActionEvent actionEvent) {+
    CloseIconInterface bean = getBean();
    bean.closeIcon(actionEvent);
    +}+
    4) Generated the jar.
    5) Removed the oracle provided default dynamicTabTemplate jar and instead added my custom generated jar to the application
    6) Applied the new template
    7) Set all the attributes along with the new closeTab attribute. This would take the BackingBean name...example: <f:attribute name="closeTab" value="#{xxxScope.xxxBean}"/>
    8) Made xxxBean to implement CloseTabInterface
    9) Implemented the closeIcon method with custom code to confirm page close before removing the Tab.
    However like you said, i'll keep tab on future updates to the default tab template updates to not miss any bug fixes or enhancements.
    Thanks everyone who looked into this for me and Hope this helps someone else :)...Good luck !

  • How can I enable the center mouse click to open and close tabs in Firefox and Chrome?

    I have a MacBook Pro Model A1261 purchased in 2009. On my other mac at work (and my PC) I can center click to open a link in a new tab while in Chrome or FireFox, and also to close a tab by clicking on it in the tabs at the top. I am using an external USB mouse on my MacBook Pro and when I click the center scroll wheel it brings up the dashboard. I looked in the settings but wasn't able to find a way to change that setting for the center button to open and close tabs in my web browser. Is there a way? Please help!

    You can restore the zoom feature by changing the values of the related prefs on the <b>about:config</b> page.
    * browser.gesture.pinch.in -> <b>cmd_fullZoomReduce</b>
    * browser.gesture.pinch.in.shift -> <b>cmd_fullZoomReset</b>
    * browser.gesture.pinch.out -> <b>cmd_fullZoomEnlarge</b>
    * browser.gesture.pinch.out.shift -> <b>cmd_fullZoomReset</b>
    * browser.gesture.pinch.latched -> <b>false</b>
    *http://kb.mozillazine.org/about:config
    See also:
    *pinchy: https://addons.mozilla.org/firefox/addon/pinchy/

  • Where did Close Tab and Close Window under the File tab go? I end up with all these open windows or exiting altogether.

    Under the File tab, I no longer see Close Tab or Close Window. Thus, I end up with a lot of open windows, because if I click File Exit, I'm logged out.

    You need to create a file userChrome.css in the chrome folder in the [http://kb.mozillazine.org/Profile_folder_-_Firefox Firefox Profile Folder] and paste the above posted code in the file.<br />
    You can use the ChromEdit Plus extension to make it easier to edit the file.
    You can access the profile folder via this button:
    *Help > Troubleshooting Information > Profile Directory: Open Containing Folder
    That code will cause all hidden menu entries to get visible all the time, so you can use the mouse to open the menus and do not need to use the keyboard.

  • Firefox did an automatic update to 6.01, and now my middle mouse button is not working in the browser. It doesn't close tabs, it doesn't open new tabs by middle clicking a link, it doesn't allow me to middle click to scroll the page...

    Firefox did an automatic update to 6.01, and now my middle mouse button is not working in the browser. It doesn't close tabs, it doesn't open new tabs by middle clicking a link, it doesn't allow me to middle click to scroll the page..

    [BUG FIXED, see "EDIT 2" at the end of my post]
    I'm on Firefox 3.6.21, and I got this problem today after a Greasemonkey update (To version 0.9.10, apparently).
    Disabling Greasemonkey solved the problem, and re-enabling it reproduced the problem (middle-clicking links to open in new tab did not work, merely highlighted the link).
    I should also note that while Greasemonkey was enabled and the bug was affecting me, Ctrl+Click to open links in new tabs was also broken.
    I hope this helps!
    EDIT: It appears this is a known incompatibility/conflict bug between current versions of Greasemonkey and Tab Mix Plus. Read more here:
    https://github.com/greasemonkey/greasemonkey/issues/1406
    EDIT 2: GREASEMONKEY HAS NOW BEEN UPDATED with a workaround to fix the problem. Go to https://addons.mozilla.org/en-US/firefox/addon/greasemonkey/versions/ to install the update manually. It hasn't been reviewed by Mozilla yet, so it won't be an automatic update for another day or two. All credit to "cannonfodder" below for noticing this; please mark his post as helpful!

  • When I open a new page, Firefox won't let me close it without closing altogether the website I am exploring. This has happened since the "update" and happened on multiple website. What happened to "close tab?"

    I used to be able to click "File" and "close tab" to close a page without closing a website. For a few weeks after the last Firefox update, I had to hit "exit" and that worked the same, but now it closes everything. Very irritating and time-consuming.
    How do I close just the one page/pdf/document that I am looking at without closing out the website or my browser altogether?

    See this article for some suggestions: [[Firefox has just updated tab shows each time you start Firefox]]
    See also http://kb.mozillazine.org/Preferences_not_saved and [[Preferences are not saved]]
    [[How to set the home page]]: Firefox supports multiple home pages separated by '|' symbols

  • Close tab groups actually closes tabs rather than just the grouping. How do I recover all tabs, not just the last 10? Pages and tabs are not in recent history.

    I had a problem with tab groups - if I mistakenly close tab groups, I can only recover the last 10 tabs.
    I had a window with many more than 10 tabs which I reopened each session by going to History > Recently Closed Windows. I knew this was risky - I could lose this if I did not keep it in an open window or recently closed window. So I was looking for a way to save this window with all the tabs. I looked into tab groups and, not knowing what I was doing, I closed the groups of tabs. There seems to be no recovery for other than the last 10 tabs. And open tabs are not necessarily in recent history if I have not accessed the tab and refreshed.

    I don't use tab groups myself, but I know of a way to increase the number of closed tabs that Firefox remembers. Unfortunately, it's not retroactive...
    (1) In a new tab, type or paste '''about:config''' in the address bar and press Enter. Click the button promising to be careful.
    (2) In the search box above the list, type or paste '''sess''' and pause while the list is filtered
    (3) Double-click the following preferences and enter the preferred new value:
    (A) '''browser.sessionstore.max_tabs_undo''' (default: 10)
    (B) '''browser.sessionstore.max_windows_undo''' (default: 3)
    Regarding what is in history, by default, Firefox will load tabs on demand when you restore a session, rather than loading every single tab immediately. If you turned off that setting, or if you visited all the tabs, then those pages should be in history, but finding them amidst all the others would be quite a challenge...

  • With multiple tabs open, I use to click File, close tab---now close tab is missing and I exit out of Firefox completely. How do I get that choice back "close tab" in the "File" drop down? Thanks. George C.

    The drop down "FILE" in the tool bar use to have a choice to "CLOSE TAB". This is now missing so when I have multiple tabs open and I want to close the most recent, I cannot. I then get warned that I will be closing multiple numbers of tabs, but there is no other choice.
    How do I get the "CLOSE TAB" back in the drop down "FILE" in the tool bar

    Start Firefox in <u>[[Safe Mode]]</u> to check if one of the extensions is causing the problem (switch to the DEFAULT theme: Firefox (Tools) > Add-ons > Appearance/Themes).
    * Don't make any changes on the Safe mode start window.
    * https://support.mozilla.com/kb/Safe+Mode
    * [[Troubleshooting extensions and themes]]

  • Unable to close tabs

    Hi,
    Recently, tonight, I've noticed issues trying to close tabs. Clicking the 'x' does not work, going to file - > close tab, nor does Ctrl+W. I think earlier I had to open the task manager to shut down the program.
    Extensions/add-ons I am running are personas, Norton IPS, Norton toolbar, and Adblock Plus 1.31. I am running Windows 7 on a 3 months old laptop. All updates should be current.
    The only thing I have installed tonight is Google Earth. That might have been a reinstall... or an over install. I actually noticed some issues with that earlier as well but I can't seem to remember them

    Please read this whole message before doing anything.
    This procedure is a diagnostic test. It won’t solve your problem. Don’t be disappointed when you find that nothing has changed after you complete it.
    The purpose of this exercise is to determine whether the problem is caused by third-party system modifications that load automatically at startup or login. First, disconnect all wired peripherals except keyboard, mouse, monitor, and Ethernet, if applicable. Boot in safe mode and log in to the account that has the problem. The instructions provided by Apple are as follows:
    Be sure your Mac is shut down.
    Press the power button.
    Immediately after you hear the startup tone, hold the Shift key. The Shift key should be held as soon as possible after the startup tone, but not before the tone.
    Release the Shift key when you see the gray Apple icon and the progress indicator (looks like a spinning gear).
    The login screen appears even if you usually log in automatically. You must know your login password in order to log in. If you’ve forgotten the password, you will need to reset it before you begin.
    Safe mode is much slower to boot and run than normal, and some things won’t work at all, perhaps including wireless networking on certain Macs. If you usually connect to the Internet via WiFi, and it doesn’t wohrk in safe mode, connect using an Ethernet cable. If you can’t do that, reboot as usual (i.e., not in safe mode) and perform a safe login, as follows: Enter your credentials at the login screen, then hold down the shift key and click the “Log in” button. Keep holding the key until the menu bar appears. In this mode, your login items, among other things, won’t load.
    In safe mode, test again. Same problem(s) now?
    After testing, reboot (if you booted in safe mode) or log out/log in (if you performed a safe login) as usual.

  • Firefox asks (twice) to save and close tabs, on new open windows without tabs, when i close them.

    About one month ago, i started to receive a message box from firefox, asking if i wanted to save and close tabs, on newly open windows (and pop-ups) without any tabs open on them.
    And everytime i close the windows without tabs, firefox asks it twice...
    I did not made any changes, so i don't know why it started doing this.

    Start Firefox in [[Safe Mode]] to check if one of the add-ons is causing the problem (switch to the DEFAULT theme: Tools > Add-ons > Themes).
    * Don't make any changes on the Safe mode start window.
    See:
    * [[Troubleshooting extensions and themes]]
    * [[Troubleshooting plugins]]
    If it does work in Safe-mode then disable all extensions and then try to find which is causing it by enabling one at a time until the problem reappears.
    * Use "Disable all add-ons" on the [[Safe mode]] start window to disable all extensions.
    * Close and restart Firefox after each change via "File > Exit" (Mac: "Firefox > Quit"; Linux: "File > Quit")

  • On my MacBook Pro, sometimes when I click to close tabs in Safari the button will not work.  I have to click on some other part of the screen and then it will.  This happens in other programs like Word/Excel for changing font, etc. Solution/Suggestions?

    On my MacBook Pro, sometimes when I click to close tabs in Safari the button will not work.  I have to click on some other part of the screen and then it will.  This happens in other programs like Word/Excel for changing font, etc. Solution/Suggestions?

    Start up in Safe Mode.
    http://support.apple.com/kb/PH4373

  • HT2490 the "X" to close tabs on my macbook is gone how do I get it back to work again

    the "X" to close tabs on my macbook is gone how do I get it back to work again

    If you lost sounds for keyboard clicks, games or other apps, email notifications and other notifications, system sounds may have been muted.
    System sounds can be muted and controlled two different ways. The screen lock rotation can be controlled in the same manner as well.
    Settings>General>Use Side Switch to: Mute System sounds. If this option is selected, the switch on the side of the iPad above the volume rocker will mute system sounds.
    If you choose Lock Screen Rotation, then the switch locks the screen. If the screen is locked, you will see a lock icon in the upper right corner next to the battery indicator gauge.
    If you have the side switch set to lock screen rotation then the system sound control is in the control center if you are running iOS 7. Swipe up from the bottom of the screen to get to control center . Tap on the bell icon and system sounds will return.
    If you are running iOS 5 or iOS 6, the system sound control is in the task bar at the bottom. Double tap the home button and swipe all the way to the right in the task bar to get to the speaker icon on the left side. Tap on that and the sounds will return.
    If you have the side switch set to mute system sounds, then the screen lock can be accessed in the same manner as described above.
    This support article from Apple explains how the side switch works.
    http://support.apple.com/kb/HT4085

Maybe you are looking for

  • Number of samples read is not equal to number of AI Sample Clock pulses - why?

    Dear Community, I am using several PXI-4472s for acquisition and at the same time I am routing the AI Sample Clock signal to a PXI-6608 counter/timer card so that I can time stamp each sample. Unfortunately I am finding that I always get more AI Samp

  • Spotlight Indexing Problem

    I've been scouring the internet looking in forum after forum for the answer to this problem for several hours now. I've tried all the usual fixes (which I will detail below) and none of them seem to be working. I recently installed Leopard from Tiger

  • IVI specific drivers usage in Teststand

    Hi, I am using Teststand 2.0.1 and i want to use some of the IVI specific drivers in my application. Can somebody guide me how to do that. Another clarification, if we use the IVI drivers which fall into any of the classes how do we achieve the inter

  • Load several cubes are different

    Hi I have a problem with loads. I have a DSO, it has 15 millon records, and i am trying to load the data to 2 different cubes, filtering by period range (ie. 1 to 3), and both load extract different quantity of records. For example, the extraction fr

  • Ethernet slow to connect after waking from sleep

    Since installing Lion (and updating to 10.7.1) on my 2008 24" iMac I have noticed that after waking from sleep the internet connection takes about 10 seconds to restore. I have reset the SMC and PRAM and performed a safe boot (in case this helped) bu