如何在此示例中使用SwingWorker

时间:2014-03-31 17:00:21

标签: java jtable swingworker

我在JTable内有阅读文件和上传信息的课程,所以当你有类似的东西时,你的应用程序会变得很慢,你将不得不使用SwingWorker。我试图跟随我的朋友[SwingWorker] [1]导师和sun API,但这是第一次看到SwingWorker第一次知道它,所以我试图复制导师,但当然有一个问题代码已发布

我的方式是更改原始代码。 (第一个代码块)到另一个

    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;
更改已编辑[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);
}
}

动作代码已修改[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);
                    */
        }
    };

更改代码后,我收到此错误,它说实现所有抽象方法 的编辑了[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.

完整的课程

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

}

}   

我有这方面的问题

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

也是这部分

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

这里说它使类抽象

 class Worker extends SwingWorker<DefaultTableModel, Void>

你也再次申报了jtable,但是在gui类的承包商中宣布了

1 个答案:

答案 0 :(得分:0)

立即修复

来自documentation of SwingWorker

  

类型参数:

     

T - 由此返回的结果类型   SwingWorker的doInBackground并获取方法
  V - 用于的类型   通过SwingWorker的发布和执行中间结果   过程方法

所以替换

class Process extends SwingWorker<String, String>

class Process extends SwingWorker<DefaultTableModel, Void>

注意:

  • 如果您从Process重命名您的课程,那就更好了,java中已经有一个名为[Process][2]的课程。
  • 您必须通过String的{​​{1}}构造函数传递。 (在这种情况下,将它作为SwingWorker类的成员并在构造函数中传递它。

致电Process

SwingWorker方法中,替换

actionPerformed

DefaultTableModel model = createModel(srtPath);

在后台进行

现在一切正常,但你没有达到预期的效果。 ui线程仍在等待输出。

  • Process p = new Process(srtPath); p.extecute(); DefaultTableModel model = p.get(); // Rest of actionPerformed content. 方法中做最后一件事execute方法。 (Ui线程将被释放。)
  • 归还actionPerformed后的其他所有内容都应放在DefaultModel doneSwingWorker)的重写Process方法中。 (您需要从构造函数传递所需的对象)。

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

    您必须从table的限制器传递Process个对象。

因此在actionPerformed

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

希望这有帮助。


修改
构造函数就像是跟随。

class Worker扩展了SwingWorker {

   private String srtPath;
   private JTable table;

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

   // Other methods.
}