Domanda

There is a java swing application that I need to automate one of the functions of. It's quite simple - the user clicks a button in the swing application and starts an action.

I made a small java application that includes the java swing application as a .jar and calls the action behind the button (read).

The problem is - in case of an exception, the swing .jar shows JOptionPane, which halts the automated execution. Is it possible to somehow override this behavior without altering the original jar?

Application structure:

Main.java

import com.swingapp.ui

public static void main(String[] args){
Swingapp.read();
}

Then the read() function in the Swingapp library:

public void read(){
try{
//do a bunch of stuff...
} catch (Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage()); // In case of an exception, the swing application will show a message dialog. This halts the automated execution of my java task, I'd like to just skip this
}

When exception happens in above application, user is expected to click "OK". But running this as automated task, nobody there to click okay

È stato utile?

Soluzione

Since a JOptionPane gains focus as soon as it opens (I think the most right button gets the focus, but it does not matter in your case) you can do the following:

Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {

        @Override
        public void eventDispatched(AWTEvent arg0) {
            Component c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
            while(c != null) {
                if (c instanceof JOptionPane) {
                    try {
                        new Robot().keyPress(KeyEvent.VK_ENTER);
                    } catch (AWTException e) {
                        e.printStackTrace();
                        break;
                    }
                }
                c = c.getParent();
            }

        }
    }, AWTEvent.FOCUS_EVENT_MASK);

It will traverse up to see if anything in the current hierarchy is an instance of JOptionPane. If so -> simulate that the user pressed Enter (Return) which will close the dialog even if the focus is in an input field.

Altri suggerimenti

I have following solution for you. You need to registrate a listener to monitor all window events. Use Toolkit.getDefaultToolkit().addAWTEventListener(). If you get a window opened event, try to check whether the window is a JDialog and whether the dialog's contentPane contains an instance of JOptionPane. If yes you need traverse the component tree, find the first button and click it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top