Java SwingWorker передает аргументы и возвращает - PullRequest
0 голосов
/ 13 марта 2012

Я хотел бы передать String s, ArrayList<String> als и вернуться ArrayList<String> als

Run.java

class Run extends SwingWorker<String, Void>
{
    private ArrayList<String> als;
    private String s;


    public Run(String s, ArrayList<String> als) {
       this.s = s;
       this.als = als;
    }

    public String doInBackground()
    {
        return AnotherClass.doSomething(s, als);
    }

    public void done()
    {
        try 
        { 
        } 
        catch (Exception ignore) 
        {
        }
    }
}

AnotherClass.java

public class AnotherClass{
    public static String doSomething(String ipRange, ArrayList<String> nmapPorts) {
        //do some stuff with the strings
        try{
            ProcessBuilder builder = new ProcessBuilder("someexe", "flag", cmds,
            "&cd");
            builder.redirectErrorStream(true);
            Process pr = builder.start();
            //do some stuff with the stream.
            return aString;
        }catch (IOException e){}
    }
}

1 Ответ

0 голосов
/ 13 марта 2012

Поскольку вы инициализировали членов своего класса в конструкторе, вы всегда можете использовать глобальные переменные в SwingWorker.

class Run extends SwingWorker<List<String>, Void, Void>
{
private ArrayList<String> als;
private String s;


public Run(String s, ArrayList<String> als) {
   this.s = s;
   this.als = als;
}

public String doInBackground()
{
    //this is right way to do it and you are correct here.
    //Following called method must return ArrayList<String> 
    return AnotherClass.doSomething(s, als);
}

public void done()
{
    ArrayList<String> retList = null;
    try 
    { 
         //When doInBackground finishes done method is called and to get data from doInBackground it uses following method
         retList = get();
         als = retList;
    } 
    catch (Exception ignore) 
    {
    }
}

}

...