2017-04-13 36 views
-1

我有一个类从一个文件夹执行复制,首先以.txt加载的文件列表进行复制,然后复制到临时文件夹。我想说明的文件复制到文件夹,反之亦然JProgressBar显示另一个类的状态void

的进步这是我的副本等级:

public class CopyService { 

private String _destLocation; 
private List<File> _filePaths = new ArrayList<File>(); 
private Map<String, String> _fileProperties = new HashMap<String, String>(); 
private String _rootLocation; 

private File _txtFile; 

public CopyService() { 
setRootLocation(NekretnineService.getRootFolder()); 
setDestLocation(NekretnineService.getDestFolder()); 
} 

public void copyImagesToTempFolder() throws IOException { 
File destLocationFolder = new File(getDestLocation()); 
if (getFilePaths() != null) { 
    if (!destLocationFolder.exists()) { 
    destLocationFolder.mkdir(); 
    } 
    for (File f : getFilePaths()) { 
    if (f.exists()) { 
     FileUtils.copyFileToDirectory(f, destLocationFolder); 
    } 
    } 
} 
} 

public String getDestLocation() { 
return _destLocation; 
} 

public List<File> getFilePaths() { 
return _filePaths; 
} 

public Map<String, String> getFileProperties() { 
return _fileProperties; 
} 

public String getRootLocation() { 
return _rootLocation; 
} 

public File getTxtFile() { 
return _txtFile; 
} 

public void loadTxtFile(File txtFile) throws Exception { 
try { 
    int lines = 0; 
    List<String> imgNames = new ArrayList<String>(); 
    try (BufferedReader br = new BufferedReader(new FileReader(txtFile))) { 
    String txtLine; 
    while ((txtLine = br.readLine()) != null) { 
     imgNames.add(txtLine); 
     lines++; 
    } 
    } 
    for (String img : imgNames) { 
    String fullPath = getRootLocation(); 
    fullPath += File.separator + img; 
    getFilePaths().add(new File(fullPath)); 
    fullPath = ""; 
    } 
    _fileProperties.put("filename", txtFile.getName()); 
    _fileProperties.put("filesize", String.valueOf(txtFile.length())); 
    _fileProperties.put("totalimgs", String.valueOf(lines)); 
} catch (Exception e) { 
    System.out.println(e.getMessage()); 
} 
} 

public void setDestLocation(String destLocation) { 
_destLocation = destLocation; 
} 

public void setFilePaths(List<File> filePaths) { 
_filePaths = filePaths; 
} 

public void setFileProperties(Map<String, String> fileProperties) { 
_fileProperties = fileProperties; 
} 

public void setRootLocation(String rootLocation) { 
_rootLocation = rootLocation; 
} 

public void setTxtFile(File txtFile) { 
_txtFile = txtFile; 
} 

@Override 
public String toString() { 
return "CopyService [_destLocation=" + _destLocation + ", _filePaths=" + _filePaths + ", _fileProperties=" 
    + _fileProperties + ", _rootLocation=" + _rootLocation + ", _txtFile=" + _txtFile + "]"; 
} 

}

这是与窗口建设者使我的GUI窗口:

public class MainWindow extends JFrame { 

private static final long serialVersionUID = 1L; 
private JPanel _contentPane; 
private CopyService copyService; 
private JLabel lblFileName; 
private JLabel lblFileSize; 
private JLabel lblImagesCount; 
private JTextField txtImgDestination; 
private JTextField txtRootLocation; 

public MainWindow() { 
Image img = new ImageIcon(getClass().getClassLoader().getResource("ico_house.png")).getImage(); 
setIconImage(img); 
setSize(450, 341); 
setTitle("Nekretnine Service"); 
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
setBounds(100, 100, 450, 300); 
setLocationRelativeTo(null); 
_contentPane = new JPanel(); 
_contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
setContentPane(_contentPane); 
_contentPane.setLayout(null); 

JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP); 
tabbedPane.setBounds(0, 0, 434, 261); 
_contentPane.add(tabbedPane); 

JPanel backupTab = new JPanel(); 
tabbedPane.addTab("Backup", null, backupTab, null); 

JPanel imgCleanerTab = new JPanel(); 
tabbedPane.addTab("Image Cleaner", null, imgCleanerTab, null); 
imgCleanerTab.setLayout(null); 

JPanel panel = new JPanel(); 
panel.setBorder(new BevelBorder(BevelBorder.LOWERED, Color.BLACK, null, null, null)); 
panel.setBounds(10, 11, 409, 73); 
imgCleanerTab.add(panel); 
panel.setLayout(null); 

lblFileName = new JLabel("Filename:"); 
lblFileName.setBounds(20, 11, 247, 14); 
panel.add(lblFileName); 
lblFileName.setFont(new Font("Tahoma", Font.BOLD, 11)); 

lblFileSize = new JLabel("Size:"); 
lblFileSize.setBounds(20, 30, 247, 14); 
panel.add(lblFileSize); 
lblFileSize.setFont(new Font("Tahoma", Font.BOLD, 11)); 

lblImagesCount = new JLabel("Total images to copy:"); 
lblImagesCount.setBounds(20, 49, 247, 14); 
panel.add(lblImagesCount); 
lblImagesCount.setFont(new Font("Tahoma", Font.BOLD, 11)); 

JButton btnCopyBack = new JButton("Copy to location"); 
btnCopyBack.setEnabled(false); 
btnCopyBack.setFont(new Font("Tahoma", Font.PLAIN, 12)); 
btnCopyBack.setBounds(10, 165, 200, 23); 
imgCleanerTab.add(btnCopyBack); 

JButton btnDelete = new JButton("Clean images folder"); 
btnDelete.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
    btnCopyBack.setEnabled(true); 
    } 
}); 
btnDelete.setEnabled(false); 
btnDelete.setFont(new Font("Tahoma", Font.PLAIN, 12)); 
btnDelete.setBounds(10, 131, 200, 23); 
imgCleanerTab.add(btnDelete); 

JButton btnCopyImagesToTemp = new JButton("Copy images to temp folder"); 
btnCopyImagesToTemp.setEnabled(false); 
btnCopyImagesToTemp.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
    try { 
     copyService.copyImagesToTempFolder(); 
     btnDelete.setEnabled(true); 
    } catch (IOException e1) { 
     JOptionPane.showMessageDialog(_contentPane, "File error " + e1.getMessage(), "Error", 
      JOptionPane.ERROR_MESSAGE); 
    } 
    } 
}); 
btnCopyImagesToTemp.setFont(new Font("Tahoma", Font.PLAIN, 12)); 
btnCopyImagesToTemp.setBounds(10, 97, 200, 23); 
imgCleanerTab.add(btnCopyImagesToTemp); 

JButton btnFileList = new JButton("Images List"); 
btnFileList.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
    new FileList(copyService.getFilePaths()).setVisible(true); 
    } 
}); 
btnFileList.setEnabled(false); 
btnFileList.setBounds(276, 7, 123, 23); 
panel.add(btnFileList); 

JButton btnLoadTxtFile = new JButton("Load .txt File"); 
btnLoadTxtFile.addActionListener(new ActionListener() { 
    @SuppressWarnings("static-access") 
    public void actionPerformed(ActionEvent e) { 
    try { 
     JFileChooser jf = new JFileChooser("C:\\"); 
     FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES", "txt", "text"); 
     jf.setFileFilter(filter); 
     int status = jf.showOpenDialog(_contentPane); 
     if (status == jf.APPROVE_OPTION) { 
     copyService = new CopyService(); 
     copyService.loadTxtFile(jf.getSelectedFile()); 
     lblFileName.setText("Filename:" + " " + copyService.getFileProperties().get("filename")); 
     lblFileSize.setText("Size:" + " " + copyService.getFileProperties().get("filesize") + " b"); 
     lblImagesCount.setText(
      "Total images to copy:" + " " + copyService.getFileProperties().get("totalimgs")); 
     btnFileList.setEnabled(true); 
     btnCopyImagesToTemp.setEnabled(true); 

     } else { 
     JOptionPane.showMessageDialog(_contentPane, "Error while choosing file", "Error", 
      JOptionPane.ERROR_MESSAGE); 
     } 

    } catch (Exception e1) { 
     JOptionPane.showMessageDialog(_contentPane, "File error " + e1.getMessage(), "Error", 
      JOptionPane.ERROR_MESSAGE); 
    } 
    } 
}); 
btnLoadTxtFile.setBounds(277, 45, 123, 23); 
panel.add(btnLoadTxtFile); 

JProgressBar progressBar = new JProgressBar(); 
progressBar.setBounds(10, 199, 409, 23); 
imgCleanerTab.add(progressBar); 

JPanel confifgTab = new JPanel(); 
tabbedPane.addTab("Settings", null, confifgTab, null); 
confifgTab.setLayout(null); 

JButton btnSaveSettings = new JButton("Save Settings"); 
btnSaveSettings.setFont(new Font("Tahoma", Font.BOLD, 12)); 
btnSaveSettings.setBounds(294, 202, 125, 20); 
confifgTab.add(btnSaveSettings); 

txtRootLocation = new JTextField(); 
txtRootLocation.setEditable(false); 
txtRootLocation.setBounds(10, 34, 259, 20); 
confifgTab.add(txtRootLocation); 
txtRootLocation.setColumns(10); 

JLabel lblNewLabel = new JLabel("Root folder for images:"); 
lblNewLabel.setBounds(10, 11, 140, 14); 
confifgTab.add(lblNewLabel); 

JButton btnSelectRootFolder = new JButton("Select Folder"); 
btnSelectRootFolder.setBounds(279, 33, 140, 23); 
confifgTab.add(btnSelectRootFolder); 

txtImgDestination = new JTextField(); 
txtImgDestination.setEditable(false); 
txtImgDestination.setColumns(10); 
txtImgDestination.setBounds(10, 88, 259, 20); 
confifgTab.add(txtImgDestination); 

JLabel lblDestinationFolderFor = new JLabel("Destination folder for images:"); 
lblDestinationFolderFor.setBounds(10, 65, 259, 14); 
confifgTab.add(lblDestinationFolderFor); 

JButton btnSelectDestFolder = new JButton("Select Folder"); 
btnSelectDestFolder.setBounds(279, 87, 140, 23); 
confifgTab.add(btnSelectDestFolder); 
} 

public JTextField getTxtImgDestination() { 
return txtImgDestination; 
} 

public JTextField getTxtRootLocation() { 
return txtRootLocation; 
}} 

我想在进度条上显示复制进度,但我不知道如何实现它,我只知道复制方法与gui在同一个类中。

+1

http://stackoverflow.com/help/mcve –

+2

1)见[检测/修复一个代码块的吊闭括号]( HTTP://meta.stackexchange。com/q/251795/155831),因为我不能再纠缠于这个问题。 2)@JaroslawPawlak伟大的想法和一个提示:在评论汽车中的[mcve]'扩展到[mcve]。少打字相同/更多的细节。 ;)3)Java GUI必须在不同的语言环境中使用不同的PLAF来处理不同的操作系统,屏幕大小,屏幕分辨率等。因此,它们不利于像素的完美布局。相反,使用布局管理器或[它们的组合](http://stackoverflow.com/a/5630271/418556).. –

+0

..以及布局填充和边框[white space](http://stackoverflow.com /一个/418556分之17874718)。 –

回答

4

您将希望允许外部类在复制文件时监听CopyService类状态的变化,但幸运的是Java和Swing具有此机制,但需要您付出一些努力来学习如何使用这些库。 Suggestsion:

  • 给这个CopyService类SwingPropertyChangeSupport私有实例字段,并初始化实例,传递this,当前类。该对象具有允许它接受侦听器的机制,然后编码人员可以通过调用其方法来通知这些侦听器对该类中状态的更改。
  • 为该类指定一个public void addPropertyChangeListener(PropertyChangeListener l)委托方法,并在方法内部将侦听器添加到SwingPropertyChangeSupport实例。
  • 类提供一个公共常量字符串,说public static final String COPY = "copy";
  • 里面的copyImagesToTempFolder方法,增加一个计数器变量,然后通知已通过调用其firePropertyChange方法与SwingPropertyChangeSupport实例注册的所有侦听器。 Bound Properties Tutorial可以帮助你的细节。
  • 您的MainWindow类是否通过调用它的addPropertyChangeListener(...)方法并传入有效的PropertyChangeListener(再次检查上面链接的教程)来为其CopyService实例注册侦听器。
  • 在此属性内部更改侦听器,获取状态更改信息并使用它更新JProgressBar。
  • 重要的是,在后台线程中调用copyImagesToTempFolder(...)方法 - 为此使用SwingWorker,本教程将帮助您完成此操作:Lesson: Concurrency in Swing。如果您不使用后台线程,那么文件更改过程将阻止Swing事件线程,从而有效地冻结您的GUI并阻止进度条进展。

另一个也许更好的选择是让您的CopyService类扩展SwingWorker,然后使用已经连接到SwingWorker中的相同侦听器机制来实现您的目标。

例如:

import java.awt.event.ActionEvent; 
import java.awt.event.KeyEvent; 
import java.beans.PropertyChangeEvent; 
import java.beans.PropertyChangeListener; 
import java.io.File; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.concurrent.ExecutionException; 
import java.util.concurrent.TimeUnit; 

import javax.swing.*; 

@SuppressWarnings("serial") 
public class ProgressMcve extends JPanel { 
    private JProgressBar progressBar = new JProgressBar(0, 100); 
    private CopyAction copyAction = new CopyAction(); 

    public ProgressMcve() { 
     progressBar.setStringPainted(true); 

     add(progressBar); 
     add(new JButton(copyAction)); 
    } 

    private class CopyAction extends AbstractAction { 
     public CopyAction() { 
      super("Copy"); 
      putValue(MNEMONIC_KEY, KeyEvent.VK_C); 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      setEnabled(false); 
      progressBar.setValue(0); 
      MockCopyService copyService = new MockCopyService(); 
      copyService.addPropertyChangeListener(new CopyServiceListener()); 
      copyService.execute(); 
     } 
    } 

    private class CopyServiceListener implements PropertyChangeListener { 
     @Override 
     public void propertyChange(PropertyChangeEvent evt) { 
      if ("progress".equals(evt.getPropertyName())) { 
       int progress = (int) evt.getNewValue(); 
       progressBar.setValue(progress); 
      } else if (SwingWorker.StateValue.DONE == evt.getNewValue()) { 
       progressBar.setValue(100); 
       progressBar.setString("Done"); 
       copyAction.setEnabled(true); 
       try { 
        ((MockCopyService) evt.getSource()).get(); 
       } catch (InterruptedException | ExecutionException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 

    private static void createAndShowGui() { 
     ProgressMcve mainPanel = new ProgressMcve(); 

     JFrame frame = new JFrame("ProgressMcve"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(() -> createAndShowGui()); 
    } 
} 

// simple MCVE example class that mocks the functioning of your class 
public class MockCopyService extends SwingWorker<Void, Integer> { 
    public static final String COPY = "copy"; 
    private List<File> fileList = new ArrayList<>(); 

    public MockCopyService() { 

    } 

    public int getFileListSize() { 
     // the real return: 
     // return fileList.size(); 

     // the mock return: 
     return 10; 
    } 

    public void copyImagesToTempFolder() { 
     for (int i = 0; i < getFileListSize(); i++) { 
      System.out.println("copying file"); 
      int fileProgress = (100 * i)/getFileListSize(); 
      // notify listeners 
      setProgress(fileProgress); 
      try { 
       TimeUnit.SECONDS.sleep(1); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
     setProgress(getFileListSize()); 
    } 

    @Override 
    protected Void doInBackground() throws Exception { 
     copyImagesToTempFolder(); 
     return null; 
    } 
} 
+0

感谢您的解释和帮助,它可以帮助我很多! :) – tehnodrom