How to pass arguments to SwingWorker?

I am trying to implement a Swing worker in my GUI. At the moment, I have a JFrame containing a button. When this is clicked, it should update the displayed tab, and then run the program in the background thread. Here is what I still have.

class ClassA { private static void addRunButton() { JButton runButton = new JButton("Run"); runButton.setEnabled(false); runButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new ClassB().execute(); } }); mainWindow.add(runButton); } } class ClassB extends SwingWorker<Void, Integer> { protected Void doInBackground() { ClassC.runProgram(cfgFile); } protected void done() { try { tabs.setSelectedIndex(1); } catch (Exception ignore) { } } } 

I do not understand how I can pass my cfgFile object. Can anyone advise on this?

+6
source share
2 answers

Why not give it a File field and fill in this field with a constructor that accepts a File parameter?

 class ClassB extends SwingWorker<Void, Integer> { private File cfgFile; public ClassB(File cfgFile) { this.cfgFile = cfgFile; } protected Void doInBackground() { ClassC.runProgram(cfgFile); } protected void done() { try { tabs.setSelectedIndex(1); } catch (Exception ignore) { // *** ignoring exceptions is usually not a good idea. *** } } } 

And then run it like this:

 public void actionPerformed(ActionEvent e) { new ClassB(cfgFile).execute(); } 
+19
source

Use the constructor to pass the parameter. For example, for example:

 class ClassB extends SwingWorker<Void, Integer> { private File cfgFile; public ClassB(File cfgFile){ this.cfgFile=cfgFile; } protected Void doInBackground() { ClassC.runProgram(cfgFile); } protected void done() { try { tabs.setSelectedIndex(1); } catch (Exception ignore) { } } 

}

+1
source

Source: https://habr.com/ru/post/900081/


All Articles