JTabbedPane: Actions performed before displaying s

2019-05-02 06:09发布

问题:

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?

回答1:

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


回答2:

The action to change the tab is triggered by a mouse listener in the UI class. it goes through and checks whether there is a tab at the clicked coordinate and if so, whether the tab is enabled. If that criteria is met, it will call setSelectedIndex(int) on your JTabbedPane. In order to intercept the tab changing, what you can do is override setSelectedIndex(int) to trigger a permissions check. Once the permissions are validated, you can make a call to super.setSelectedIndex(int). this should do what you want.

please note that if the permissions check is a long running call (ie a call to a database or a server), you should use something like a SwingWorker break up your processing, so that the permissions check is done off the AWT EventQueue and the call to super.setSelectedIndex(int) is done on the AWT EventQueue.