JTabbedPane: Actions performed before displaying selected tab

Raji picture Raji · Jun 30, 2009 · Viewed 8.3k times · Source

When one of the panels present in a JTabbedPane is clicked, I need to perform a few actions at the start. Say, for example, I need to check the username and password. Only if those match, the particular panel operations need to be performed. Can you suggest any methods?

Answer

Adamski picture Adamski · Jun 30, 2009

Not sure I fully understand your question, but I would do something like:

  • Add a ChangeListener to the JTabbedPane to listen for the first tab click.
  • When a ChangeEvent occurs perform the login on a background thread using a SwingWorker.
  • If the login is successful perform the required UI operations on the Event dispatch thread.

For example:

    tabbedPane.addChangeListener(new ChangeListener() {
    private boolean init;

    public void stateChanged(ChangeEvent e) {
        if (!init) {                                        
            init = true;

            new SwingWorker<Boolean, Void>() {
                @Override
                protected void done() {
                    try {
                        boolean loggedIn = get();

                        if (loggedIn) {
                            // Success so perform tab operations.
                        }
                    } catch (InterruptedException e1) {
                        e1.printStackTrace(); // Handle this.
                    } catch (ExecutionException e1) {
                        e1.printStackTrace(); // Handle this.
                    }
                }

                protected Boolean doInBackground() throws Exception {
                    // Perform login on background thread.  Return true if successful.
                    return true;
                }
            }.execute();
        }
        }
    });