简体   繁体   English

在此示例中如何使用SwingWorker

[英]How to use SwingWorker in this example

I have class for reading file and upload information inside JTable , So when you have something like that, your application will become so slow and you will have to use SwingWorker . 我有用于在JTable读取文件和上载信息的类,因此,当您遇到类似的情况时,您的应用程序将变得非常缓慢,并且您将不得不使用SwingWorker i tried to follow one of my friend [SwingWorker][1] tutor and sun API, but this is the first time of seeing SwingWorker even first time to know about it, so i tried to copy the tutor but of course there is an issue the code is posted 我试图跟随我的一个朋友[SwingWorker] [1]导师和sun API,但这是我第一次见到SwingWorker,甚至是第一次了解它,因此我尝试复制该导师,但是当然存在问题代码已发布

my way was by changing the original code. 我的方式是更改原始代码。 (the first block of code) To the other (第一段代码)

    private DefaultTableModel createModel(String srtPath) {
        //int maxLine = ReadFile.maxLine(srtPath);  // debug
        //Object[][] data = new Object[maxLine][];
        //System.out.println(maxLine);  // debug
        DefaultTableModel model = new DefaultTableModel(columnNames, 0);
        ArrayList<String> ends = ReadFile.getFileEndingTime(srtPath);
        ArrayList<String> starts = ReadFile.getFileStartingTime(srtPath);
        ArrayList<String> subs = ReadFile.readSubtitles(srtPath);
        ArrayList<String> lins = ReadFile.ArraylineLengths(srtPath);
        for (int i = 0; i < ReadFile.maxLine(srtPath); i++) {
            //System.out.println(lins.get(i)+" "+starts.get(i)+" "+ ends.get(i)+" "+ subs.get(i));
            model.addRow(new Object[] {lins.get(i), starts.get(i), ends.get(i), subs.get(i)});
        }
        return model;

code after changing Edited[2] 修改后的代码[2]

 class Worker extends SwingWorker<DefaultTableModel, Void> {
       private final String srtPath;
       private final JTable table;
       DefaultTableModel model;
        public Worker(String srtPath, JTable table) {
                this.srtPath = srtPath;
                 this.table = table;
             }

      protected DefaultTableModel doInBackground(String srtPath)  {
     model = new DefaultTableModel(columnNames, 0);
    ArrayList<String> ends = ReadFile.getFileEndingTime(srtPath);
    ArrayList<String> starts = ReadFile.getFileStartingTime(srtPath);
    ArrayList<String> subs = ReadFile.readSubtitles(srtPath);
    ArrayList<String> lins = ReadFile.ArraylineLengths(srtPath);
    for (int i = 0; i < ReadFile.maxLine(srtPath); i++) {
        model.addRow(new Object[] {lins.get(i), starts.get(i), ends.get(i), subs.get(i)});
    }
    return model;
}
    @Override
protected void done() {
    table.setModel(model);
    table.setFillsViewportHeight(true);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    TableColumn columnA = table.getColumn("#");
    columnA.setMinWidth(10);
    columnA.setMaxWidth(40);
    TableColumn columnB= table.getColumn("Start");
    columnB.setMinWidth(80);
    columnB.setMaxWidth(90);
    TableColumn columnC= table.getColumn("End");
    columnC.setMinWidth(80);
    columnC.setMaxWidth(90);
}
}

the action code Edited[2] 动作代码已编辑[2]

     Action openAction = new AbstractAction("Open Subtitle", openIcon) {
        @Override
        public void actionPerformed(ActionEvent e) {
            ourFileSelector.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            ourFileSelector.showSaveDialog(null);
            ourSrtFile =  ourFileSelector.getSelectedFile();
            srtPath = ourSrtFile.getAbsolutePath();
            Worker p = new Worker(srtPath, table);
            p.extecute();
            /*
            table.setModel(model);
            table.setFillsViewportHeight(true);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
            TableColumn columnA = table.getColumn("#");
            columnA.setMinWidth(10);
            columnA.setMaxWidth(40);
            TableColumn columnB= table.getColumn("Start");
            columnB.setMinWidth(80);
            columnB.setMaxWidth(90);
            TableColumn columnC= table.getColumn("End");
            columnC.setMinWidth(80);
            columnC.setMaxWidth(90);
                    */
        }
    };

after changing the code i am getting this error and it say implements all abstract method Edited[2] 更改代码后,我收到此错误,它说实现了所有抽象方法Edited [2]

C:\Users\isslam\Documents\NetBeansProjects\AnimeAid\src\animeaid\GuiInterface.java:129: error: cannot find symbol
                p.extecute();
  symbol:   method extecute()
  location: variable p of type GuiInterface.Worker
C:\Users\isslam\Documents\NetBeansProjects\AnimeAid\src\animeaid\GuiInterface.java:240: error: GuiInterface.Worker is not abstract and does not override abstract method doInBackground() in SwingWorker
     class Worker extends SwingWorker<DefaultTableModel, Void> {
Note: C:\Users\isslam\Documents\NetBeansProjects\AnimeAid\src\animeaid\GuiInterface.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
2 errors
C:\Users\isslam\Documents\NetBeansProjects\AnimeAid\nbproject\build-impl.xml:920: The following error occurred while executing this line:
C:\Users\isslam\Documents\NetBeansProjects\AnimeAid\nbproject\build-impl.xml:260: Compile failed; see the compiler error output for details.

the full class 全班

   public class GuiInterface extends JFrame {
    String[] columnNames = {"#", "Start", "End", "Translation column"};

    JComboBox laList;  
    ReadFile reader;
    private final int numberOfButton = 6;
    private final JTable table;
    JToolBar toolBar;
    private final JTextField enterText,startTime,endTime;
    private final JMenu jMenu1,jMenu2,jMenu3;
    private final JMenuBar jMenuBar1;
    private final JMenuItem itemNewSrt,itemOpenVideo,itemSavefile;
    private static JFileChooser ourFileSelector,ourVideoSelector;
    File ourVideoFile,ourSrtFile;
    Border Campound,empty,Boveld,etch;
    private final JLabel startTimeingLable,endTimeingLabel;
    public static String  mediaPath="",srtPath="";
    Canvas c;
    ImageIcon[] icon;
    JButton[] Obutton;
   static final int COLUMN = 4 ; 



         public static void main(String[] args) throws IOException 
       {
           //ReadFile.readSubtitles();
        NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "C:\\Program Files\\VideoLAN\\VLC");
        Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
          SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new GuiInterface("");

            }

        });

}



    public GuiInterface(String title){

    //reader = new ReadFile();

    setSize(1024, 720);
    setVisible(true);
    setTitle("AnimeFactor");
    setDefaultCloseOperation(GuiInterface.EXIT_ON_CLOSE);
    //video setting 
    MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory();
    c = new Canvas();
    String[] petStrings = { "Translation Line", "Both Line" };
    laList = new JComboBox(petStrings);
    c.setBackground(Color.black);
    JPanel p = new JPanel();
    p.setLayout(new BorderLayout());
    p.add(c, BorderLayout.CENTER);
    add(p, BorderLayout.CENTER);
    EmbeddedMediaPlayer mediaPlayer = mediaPlayerFactory.newEmbeddedMediaPlayer();
    mediaPlayer.setVideoSurface(mediaPlayerFactory.newVideoSurface(c));
    mediaPlayer.playMedia("C:\\Users\\isslam\\Downloads\\gg.mp4");
    table = new JTable(new DefaultTableModel(columnNames, 0));
    table.setFillsViewportHeight(true);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    TableColumn columnA = table.getColumn("#");
    columnA.setMinWidth(10);
    columnA.setMaxWidth(40);
    TableColumn columnB= table.getColumn("Start");
    columnB.setMinWidth(80);
    columnB.setMaxWidth(90);
    TableColumn columnC= table.getColumn("End");
        columnC.setMinWidth(80);
        columnC.setMaxWidth(90);


    ImageIcon openIcon = new ImageIcon(
                GuiInterface.class.getResource("/resources/image/folder-icon.png"));
        ImageIcon saveIcon = new ImageIcon(
                GuiInterface.class.getResource("/resources/image/red-disk-icon.png"));
        ImageIcon newIcon = new ImageIcon(
                GuiInterface.class.getResource("/resources/image/Actionsnew-icon.png"));




        Action openAction = new AbstractAction("Open Subtitle", openIcon) {
            @Override
            public void actionPerformed(ActionEvent e) {
                ourFileSelector.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                ourFileSelector.showSaveDialog(null);
                ourSrtFile =  ourFileSelector.getSelectedFile();
                srtPath = ourSrtFile.getAbsolutePath();
                Worker p = new Worker(srtPath, table);
                p.extecute();
                DefaultTableModel model = p.get();
                table.setModel(model);
                table.setFillsViewportHeight(true);
                table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
                TableColumn columnA = table.getColumn("#");
                columnA.setMinWidth(10);
                columnA.setMaxWidth(40);
                TableColumn columnB= table.getColumn("Start");
                columnB.setMinWidth(80);
                columnB.setMaxWidth(90);
                TableColumn columnC= table.getColumn("End");
                columnC.setMinWidth(80);
                columnC.setMaxWidth(90);
            }
        };

        Action saveAction = new AbstractAction("Save", saveIcon) {
            @Override
            public void actionPerformed(ActionEvent e) {

            }
        };
        Action newAction = new AbstractAction("New", newIcon) {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("New File");
            }
        };
    jMenu1 = new JMenu("File");
    jMenu2 = new JMenu("Video");
    jMenu3 = new JMenu("Subtitle");
    itemNewSrt = new JMenuItem(newAction);
    jMenu1.add(itemNewSrt);
    itemSavefile = new JMenuItem(saveAction);
    jMenu1.add(itemSavefile);
    jMenuBar1 = new JMenuBar();
    jMenuBar1.setBorder(etch);
    setJMenuBar(jMenuBar1);
    jMenuBar1.add(jMenu1);
    jMenuBar1.add(jMenu2);
    jMenuBar1.add(jMenu3);


    Obutton = new JButton[numberOfButton];
    etch = BorderFactory.createEtchedBorder();
    enterText = new JTextField();
    enterText.setPreferredSize(new Dimension(0,100));
    ourFileSelector = new JFileChooser();
    startTime = new JTextField();
    startTime.setPreferredSize(new Dimension(120, 20));
    startTimeingLable = new JLabel("Starting Time");
    endTimeingLabel = new JLabel("Ending Time");
    endTime = new JTextField();
    endTime.setPreferredSize(new Dimension(120, 20));
    toolBar = new JToolBar();
        //toolBar.add(Box.createHorizontalGlue());
        toolBar.setBorder(new LineBorder(Color.LIGHT_GRAY, 1));
        toolBar.add(newAction);
        toolBar.add(saveAction);


        JPanel toolBarPane = new JPanel(new BorderLayout());
        toolBarPane.add(toolBar,BorderLayout.NORTH);

        JPanel timing = new JPanel(new FlowLayout(FlowLayout.TRAILING));
        timing.add(startTimeingLable);
        timing.add(startTime);
        timing.add(endTimeingLabel);
        timing.add(endTime);
        timing.add(laList);

        empty = BorderFactory.createEmptyBorder(30, 5, 5, 5);
        Boveld = BorderFactory.createBevelBorder(BevelBorder.RAISED);
        Campound = BorderFactory.createCompoundBorder(empty,Boveld);


        JPanel textFiled = new JPanel(new BorderLayout());
        textFiled.add(timing);
        textFiled.add(enterText,BorderLayout.SOUTH);
        textFiled.setBorder(Campound);
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.SOUTH);
        add(textFiled, BorderLayout.EAST);
        add(toolBarPane,BorderLayout.PAGE_START);




        //Container cp = getContentPane();
       toolBar.add(openAction);
       itemOpenVideo = new JMenuItem(openAction);
       jMenu1.add(itemOpenVideo);
       //itemOpenVideo.addActionListener(new MenuBarMethod());

    }

    private DefaultTableModel createModel(String srtPath) {
        DefaultTableModel model = new DefaultTableModel(columnNames, 0);
        ArrayList<String> ends = ReadFile.getFileEndingTime(srtPath);
        ArrayList<String> starts = ReadFile.getFileStartingTime(srtPath);
        ArrayList<String> subs = ReadFile.readSubtitles(srtPath);
        ArrayList<String> lins = ReadFile.ArraylineLengths(srtPath);
        for (int i = 0; i < ReadFile.maxLine(srtPath); i++) {

            model.addRow(new Object[] {lins.get(i), starts.get(i), ends.get(i), subs.get(i)});
        }
        return model;
    }

    class Worker extends SwingWorker<DefaultTableModel, Void> {
       private final String srtPath;
       private final JTable table;
        public Worker(String srtPath, JTable table) {
                this.srtPath = srtPath;
                 this.table = table;
             }

      protected DefaultTableModel doInBackground(String srtPath) throws InterruptedException {
    DefaultTableModel model = new DefaultTableModel(columnNames, 0);
    ArrayList<String> ends = ReadFile.getFileEndingTime(srtPath);
    ArrayList<String> starts = ReadFile.getFileStartingTime(srtPath);
    ArrayList<String> subs = ReadFile.readSubtitles(srtPath);
    ArrayList<String> lins = ReadFile.ArraylineLengths(srtPath);
    for (int i = 0; i < ReadFile.maxLine(srtPath); i++) {
        model.addRow(new Object[] {lins.get(i), starts.get(i), ends.get(i), subs.get(i)});
    }
    return model;
}
    @Override
protected void done() {
    table.setModel(model);
    table.setFillsViewportHeight(true);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    TableColumn columnA = table.getColumn("#");
    columnA.setMinWidth(10);
    columnA.setMaxWidth(40);
    TableColumn columnB= table.getColumn("Start");
    columnB.setMinWidth(80);
    columnB.setMaxWidth(90);
    TableColumn columnC= table.getColumn("End");
    columnC.setMinWidth(80);
    columnC.setMaxWidth(90);
}
}


public class MenuBarMethod implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent a){
        Object buttonPressed=a.getSource();
       if(buttonPressed.equals(itemOpenVideo)){
        ourVideoSelector.setFileSelectionMode(JFileChooser.FILES_ONLY);
        ourVideoSelector.showSaveDialog(null);
        ourVideoFile = ourVideoSelector.getSelectedFile();
        mediaPath = ourVideoFile.getAbsolutePath();
       }
    }

}

}   

i have issue in this lines 我在这方面有问题

protected void done() {
table.setModel(model);//because model are local  

also this part 还有这部分

 p.extecute();
 DefaultTableModel model = p.get()

here it say make the class abstract 在这里它说使课堂变得抽象

 class Worker extends SwingWorker<DefaultTableModel, Void>

also you declared jtable again but in the contractor of the gui class it is declared 您也再次声明了jtable但在gui类的承包商中却声明了

Immediate fix 立即修复

From documentation of SwingWorker SwingWorker文档中

Type Parameters: 类型参数:

T - the result type returned by this SwingWorker's doInBackground and get methods T-此SwingWorker的doInBackground和get方法返回的结果类型
V - the type used for carrying out intermediate results by this SwingWorker's publish and process methods V-此SwingWorker的发布和处理方法用于执行中间结果的类型

So replace 所以更换

class Process extends SwingWorker<String, String>

with

class Process extends SwingWorker<DefaultTableModel, Void>

Note: 注意:

  • It's better if you rename your class from Process , there is already a class named [Process][2] in java. 最好是从Process重命名您的类,java中已经有一个名为[Process][2]的类。
  • You have to pass the String via SwingWorker 's constructor. 您必须通过SwingWorker的构造函数传递String (In this case, have it as a member of Process class and pass it in constructor. (在这种情况下,请将其作为Process类的成员,然后将其传递给构造函数。

Calling the SwingWorker 致电SwingWorker

In your actionPerformed method, replace 在您的actionPerformed方法中,替换

DefaultTableModel model = createModel(srtPath);

with

Process p = new Process(srtPath);
p.extecute();
DefaultTableModel model = p.get();
// Rest of actionPerformed content.

Doing it in background 在后台执行

Now everything is working, but you have not achieved the desired effect. 现在一切正常,但是您尚未达到预期的效果。 The ui thread is still waiting for the output. ui线程仍在等待输出。

  • Make execute method last thing to do in actionPerformed method. 使execute方法在actionPerformed方法中最后要做。 (Ui thread will be released.) (Ui线程将被释放。)
  • Everything else after getting returned DefaultModel should be put in overridden done method of SwingWorker ( Process ). 返回DefaultModel之后的其他所有内容都应放在SwingWorkerProcess )的重done方法中。 (You need to pass required objects from constructor). (您需要从构造函数传递所需的对象)。

     @Override protected void done() { table.setModel(model); table.setFillsViewportHeight(true); table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); TableColumn columnA = table.getColumn("#"); columnA.setMinWidth(10); columnA.setMaxWidth(40); TableColumn columnB= table.getColumn("Start"); columnB.setMinWidth(80); columnB.setMaxWidth(90); TableColumn columnC= table.getColumn("End"); columnC.setMinWidth(80); columnC.setMaxWidth(90); } 

    You have to pass table object from constrictor of Process . 您必须从Process constrictor中传递table对象。

Therefore in actionPerformed , 因此在actionPerformed

    Process p = new Process(srtPath, table);
    p.execute();

Hope this helps. 希望这可以帮助。


Edit: 编辑:
Constructor would be like following. 构造函数将如下所示。

class Worker extends SwingWorker { class Worker扩展了SwingWorker {

   private String srtPath;
   private JTable table;

   public Worker(String srtPath, JTable table) {
       this.srtPath = srtPath;
       this.table = table;
   }

   // Other methods.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM