Conor
Conor

Reputation: 395

SwingWorker Process() warning

I tried to write a simple test program using Swing, all I want to do is load a text file and display the path of the chosen text file in a text area. I keep getting a warning on the process method "never used locally" and it is not appending any text to the textbox. Maybe I'm misunderstanding something, I hope someone can help me.

code:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileNameExtensionFilter;



public class MyPanel3 extends JPanel{ 

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JTextArea jcomp;
    private JButton btn;
    private String testfile;

    public MyPanel3() {


        //construct components
        jcomp = new JTextArea (1, 1);
        jcomp.setBorder(BorderFactory.createDashedBorder(Color.BLACK)); 
        btn = new JButton ("open");

        //adjust size and set layout
        setPreferredSize (new Dimension (944, 575));
        BoxLayout layout = new BoxLayout (this, BoxLayout.Y_AXIS);
        setLayout(layout);


        //add main components
        add (jcomp);
        add (btn);


        new SwingWorker<Void, String>(){


            protected Void doInBackground(){

                //do processes...       
                btn.addActionListener(new ActionListener() {

                    public void actionPerformed(ActionEvent ae) {

                        final JFileChooser chooseFile = new JFileChooser();
                        FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt","txt");
                        chooseFile.setFileFilter(filter);
                        chooseFile.setAcceptAllFileFilterUsed(false);
                        chooseFile.setMultiSelectionEnabled(true);

                        if(ae.getSource().equals(btn))  
                        {  
                            System.out.println("do in background running");

                            int returnVal = chooseFile.showOpenDialog(MyPanel3.this);

                            if(returnVal == JFileChooser.APPROVE_OPTION) 
                            {                                                                   
                                File[] files = chooseFile.getSelectedFiles();


                                 testfile = files[0].getPath();

                                 publish(testfile);
                            }
                        }
                    }
                });

                return null;
            }


            protected void process(String s) {
                        jcomp.append(s);

            }


        protected void done() {

            try 
            {
                //System.out.println("The operation was completed");
            } 
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }


        }.execute();    
    }


    public static void main(String[] args){

        JFrame frame = new JFrame ("MyTest");
        frame.getContentPane();     
        frame.add(new MyPanel3());      
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);  
        frame.pack();
        frame.setVisible (true);               
    }
}

warning reads:

The method process(String) from the type new SwingWorker(){} is never used locally

EDIT: with help from MadProgrammer, program is now working (selecting 3 files and printing the paths as strings in the text box)

import java.awt.Color;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileNameExtensionFilter;

public class MyPanel4 extends JPanel {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private JTextArea jcomp;
    private JButton btn;


    public MyPanel4() {
        //construct components
        jcomp = new JTextArea(1, 1);
        jcomp.setBorder(BorderFactory.createDashedBorder(Color.BLACK));
        btn = new JButton("open");

        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {

                final JFileChooser chooseFile = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt", "txt");
                chooseFile.setFileFilter(filter);
                chooseFile.setAcceptAllFileFilterUsed(false);
                chooseFile.setMultiSelectionEnabled(true);

                int returnVal = chooseFile.showOpenDialog(MyPanel4.this);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    final File[] files = chooseFile.getSelectedFiles();


                    new SwingWorker<Void, String>() {

                        private String testfile1 = files[0].getPath();
                        private String testfile2 = files[1].getPath();
                        private String testfile3 = files[2].getPath();



                        protected Void doInBackground() {

                            List<String> b = new ArrayList<String>();

                            b.add(testfile1);
                            b.add(testfile2);
                            b.add(testfile3);   

                            publish(b.get(0));
                            publish(b.get(1));
                            publish(b.get(2));

                            return null;
                        }

                        @Override
                        protected void process(List<String> chunks) {

                            for (String pathname : chunks) 
                            {
                                jcomp.append(pathname + "\n");
                            }
                        }

                        protected void done() {
                            try 
                            {
                                System.out.println("Opration Completed");

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }.execute();
                }
            }
        });

        //adjust size and set layout
        setPreferredSize(new Dimension(944, 575));
        BoxLayout layout = new BoxLayout(this, BoxLayout.Y_AXIS);
        setLayout(layout);

        //add main components
        add(jcomp);
        add(btn);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("MyTest");
        frame.getContentPane();
        frame.add(new MyPanel4());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}

Upvotes: 0

Views: 459

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347314

The SwingWorker should be created inside the buttons actionPerformed method, so that when you click the button, it will run the SwingWorker

You should, also, make sure that all interactions with user interface are fine from within the context of the Event Dispatching Thread. This means you should ask the user to select the file fro within the context of the actionPerformed method and pass the result to the SwingWorked

Updated

Two additional things...

  1. You're not actually reading the file, but simply passing the name of the file to the publish method
  2. SwingWorker defines process as protected void process(List<V> chunks) but you've defined it as protected void process(String s)...mean that you are actually not overriding the SwingWorker's process method, but creating your own...

Take a look at this example to see how you might be able to use a SwingWorker to read a file...

And, update your process to have the corrected method signature...

@Override
protected void process(List<String> chunks) {
    for (String line : chunks) {
        output.append(line);
    }
}

Remember, you should, as much as possible, use the @Override annotation when you think you are overriding a method, the compiler will tell you when you are mistaken, saving you a lot of head scratching...

Upvotes: 1

lol
lol

Reputation: 3390

It should be like this:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileNameExtensionFilter;

public class MyPanel3 extends JPanel {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private JTextArea jcomp;
    private JButton btn;
    private String testfile;

    public MyPanel3() {
        //construct components
        jcomp = new JTextArea(1, 1);
        jcomp.setBorder(BorderFactory.createDashedBorder(Color.BLACK));
        btn = new JButton("open");

        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                final JFileChooser chooseFile = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt", "txt");
                chooseFile.setFileFilter(filter);
                chooseFile.setAcceptAllFileFilterUsed(false);
                chooseFile.setMultiSelectionEnabled(true);

                int returnVal = chooseFile.showOpenDialog(MyPanel3.this);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File[] files = chooseFile.getSelectedFiles();

                    testfile = files[0].getPath();

                    new SwingWorker<Void, String>() {
                        protected Void doInBackground() {
                            publish(testfile);
                            return null;
                        }

                        protected void process(String s) {
                            jcomp.append(s);
                        }

                        protected void done() {
                            try {
                                //System.out.println("The operation was completed");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }.execute();
                }
            }
        });

        //adjust size and set layout
        setPreferredSize(new Dimension(944, 575));
        BoxLayout layout = new BoxLayout(this, BoxLayout.Y_AXIS);
        setLayout(layout);

        //add main components
        add(jcomp);
        add(btn);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("MyTest");
        frame.getContentPane();
        frame.add(new MyPanel3());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}

You are running worker when you are creating panel. But you should run it when button is clicked.

Upvotes: 1

Related Questions