0

我尝试使用 Swing 编写一个简单的测试程序,我要做的就是加载一个文本文件并在文本区域中显示所选文本文件的路径。我不断收到有关“从未在本地使用”的处理方法的警告,并且它没有将任何文本附加到文本框。也许我误解了什么,我希望有人能帮助我。

代码:

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

警告内容如下:

从未在本地使用 new SwingWorker(){} 类型的方法 process(String)

编辑:在 MadProgrammer 的帮助下,程序现在正在运行(选择 3 个文件并将路径打印为文本框中的字符串)

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

2 回答 2

1

SwingWorker应该在按钮方法中创建actionPerformed,这样当您单击按钮时,它将运行SwingWorker

您还应该确保在事件调度线程的上下文中与用户界面的所有交互都正常。这意味着您应该要求用户在方法的上下文中选择文件actionPerformed并将结果传递给SwingWorked

更新

另外两件事...

  1. 您实际上并没有读取文件,而只是将文件名传递给publish方法
  2. SwingWorker定义processprotected void process(List<V> chunks)但您已将其定义为protected void process(String s)...意味着您实际上并没有覆盖SwingWorker'process方法,而是创建自己的...

看一下这个例子,看看你如何能够使用 aSwingWorker来读取文件......

并且,更新您process以具有更正的方法签名...

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

记住,当你认为你正在重写一个方法时,你应该尽可能地使用@Override注解,编译器会在你弄错时告诉你,为你省去很多麻烦......

于 2013-10-13T21:26:20.637 回答
1

它应该是这样的:

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

创建面板时,您正在运行 worker。但是您应该在单击按钮时运行它。

于 2013-10-13T21:27:44.217 回答