Обновите JProgressbar в JTable, если JCheckbox отмечен - PullRequest
0 голосов
/ 31 октября 2018

У меня проблема с обновлением прогрессбара. Если я установлю флажок, файл будет автоматически скопирован, но прогресс по-прежнему равен 0. Я использую SwingWokrer, но я не знаю, как я могу выполнить обновление индикатора прогресса. Я перепробовал много комбинаций, но это не работает.


Этот код отвечает за загрузку файла из выбранной строки.

        jTable.getModel().addTableModelListener(new TableModelListener() {
        public void tableChanged(TableModelEvent e) {
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel tableModel = (TableModel) e.getSource();

            Boolean dataObject = (Boolean) tableModel.getValueAt(row,column);
            String fileNameToCopy = (String) tableModel.getValueAt(row, 0);
            Long fileSize = (Long) tableModel.getValueAt(row, 1);
            Float progress = (Float) tableModel.getValueAt(row, 3);

            if (dataObject == true) {
                customTableData.setFile(new File(fileNameToCopy));
                customTableData.setFileSize(fileSize);
                customTableData.setProgress(progress);;
                copyFiles = new CopyFiles(customTableData);
            }

        }
    });

CustomTableData.java

public class CustomTableData {

private File file;
private long fileSize;
private Boolean edit = false;
private float progress;

public CustomTableData() {}

public File getFile() {
    return file;
}
public void setFile(File file) {
    this.file = file;
}

public long getFileSize() {
    return fileSize;
}

public void setFileSize(long fileSize) {
    this.fileSize = fileSize;
}

public Boolean isEdit() {
    return edit;
}

public void setEdit(Boolean edit) {
    this.edit = edit;
}

public float getProgress() {
    return progress;
}

public void setProgress(float progress) {
    this.progress = progress;
}

}

Мой класс CopyFiles.java

private String fileName;
private long fileSize;
private float progress;
private CustomTableData data;

public CopyFiles(CustomTableData data) {
    this.data = new CustomTableData();
    this.fileName = data.getFile().getName();
    this.fileSize = data.getFileSize();
    this.progress = data.getProgress();
    worker.execute();
}

SwingWorker<Void, Float> worker = new SwingWorker<Void, Float>(){

    @Override
    protected Void doInBackground() throws Exception {


        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(source + fileName);
            os = new FileOutputStream(destination + fileName);
            byte[] buffer = new byte[BUFFER];
            int length = 0;
            float pro = 0;
            while((length = is.read(buffer)) != -1) {
                publish(pro += length);
                os.write(buffer, 0, length);
            }
        } catch (Exception e) {
            e.getMessage();
        } finally {
            try {
                is.close();
                os.close();
            } catch (IOException e) {
                e.getMessage();
            }
        }
        return null;
    }

    protected void process(java.util.List<Float> chunks) {
        for (Float f : chunks) {
            progress = (f*100) / fileSize;
            System.out.println("Percentage progress: " + progress + " >>> file size: " + f);
        }
    };

    protected void done() {
        System.out.println("FILE: " + fileName + " SIZE: " + fileSize);
    };          
};
}

И мой класс CustomTableModel.java

public class CustomTableModel extends AbstractTableModel {

private static final long serialVersionUID = -2929662905556163705L;

@SuppressWarnings("unused")
private File dir;
private File[] fileArray;
private List<CustomTableData> filesList;
private CustomTableData fileRow;

public CustomTableModel(File dir) {
    this.dir = dir;
    this.filesList = new ArrayList<CustomTableData>();
    this.fileArray = dir.listFiles();
    fileLoop();
}

private void fileLoop() {
    for (int i = 0; i < fileArray.length; i++) {
        this.fileRow = new CustomTableData();
        if (fileArray[i].isFile()) {
            fileRow.setFile(fileArray[i]);
            fileRow.isEdit();
            fileRow.getProgress();
            filesList.add(fileRow);
        }
    }
}

private ResourceBundle resourceBundle = ResourceBundle.getBundle("MessageBundle", Locale.forLanguageTag("pl"));

protected String[] columns = new String[] {
        resourceBundle.getString("fileName"),
        resourceBundle.getString("fileSize") + " [byte]",
        resourceBundle.getString("getFile"),
        resourceBundle.getString("progress")};


@SuppressWarnings("rawtypes")
protected Class[] columnClasses = {String.class , Long.class, JCheckBox.class, JProgressBar.class};

public int getColumnCount() {
    return columns.length;
}

public int getRowCount() {
    return filesList.size();
}

public String getColumnName(int col) {
    return columns[col].toString();
}

public Class<?> getColumnClass(int c) {
    switch (c) {
    case 0:
        return String.class;
    case 1:
        return Long.class;
    case 2:
        return Boolean.class;
    case 3:
        return Float.class;
    default:
        return null;
    }
}

public Object getValueAt(int row, int col) {
    fileRow = filesList.get(row);

    switch (col) {
    case 0:
        return fileRow.getFile().getName();
    case 1:
        return fileRow.getFile().length();
    case 2:
        return fileRow.isEdit();
    case 3:
        return fileRow.getProgress();
    default:
        return null;
    }
}

public boolean isCellEditable(int row, int col) {
    switch (col) {
    case 0:
        return false;
    case 1:
        return false;
    case 2:
        return true;
    case 3:
        return false;
    default:
        return false;
    }
}   

public void setValueAt(Object aValue, int row, int column) {
    fileRow = filesList.get(row);
    if (column == 2) {
        fileRow.setEdit((Boolean)aValue);
        fireTableCellUpdated(row, column);
    }
}
}

Это мой класс ProgressBarRenderer.java

public class ProgressBarRenderer extends JProgressBar implements TableCellRenderer {

private static final long serialVersionUID = 551156559687881082L;

public ProgressBarRenderer() {
    super();
}

public ProgressBarRenderer(int min, int max) {
    super(min, max);
}

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

    setValue((int) ((Float) value).floatValue());

    return this;
}
}

Просмотр моей таблицы

1 Ответ

0 голосов
/ 09 ноября 2018

Rozwiązanie

Progressbar jest prawidłowo aktualizowany w metodzie process ()

public class CopyFiles {

private static final int BUFFER = 1024;

private int row;
private CustomTableModel customTableModel;

private String fileName;
private File file;

public CopyFiles(String fileName, CustomTableModel customTableModel, int row) {
    this.fileName = fileName;
    this.file = new File(PathEnum.SOURCE.getPath() + fileName);
    this.customTableModel = customTableModel;
    this.row = row;
    worker.execute();
}

public String getFile() {
    return file.getName();
}

public long getFileSize() {
    return file.length();
}

public SwingWorker<Void, Float> getWorker() {
    return worker;
}
    SwingWorker<Void, Float> worker = new SwingWorker<Void, Float>() {

    @Override
    protected Void doInBackground() throws Exception {

        InputStream is = null;
        OutputStream os = null;

        float progress = 0;
        try {
            is = new FileInputStream(PathEnum.SOURCE.getPath() + getFile());
            os = new FileOutputStream(PathEnum.DESTINATION.getPath() + getFile());

            byte[] buffer = new byte[BUFFER];

            long count = 0;
            int bufferLength;

            while ((bufferLength = is.read(buffer)) != -1) {
                count += bufferLength;
                os.write(buffer, 0, bufferLength);

                progress = (int) ((count * 100) / getFileSize());
                publish(progress);
            }
        } catch (Exception e) {
            e.getMessage();
        } finally {
            try {
                is.close();
                os.close();
            } catch (IOException e) {
                e.getMessage();
            }
        }
        return null;
    }

    protected void process(List<Float> chunks) {
        float currentProgress = chunks.get(chunks.size()-1);
        customTableModel.setValueAt(currentProgress, row, 3);
    };

    protected void done() {
        System.out.println("FILE: " + getFile() + " SIZE: " + getFileSize());
    };

};
...