java


Update JTextArea to show progress


I am doing an application to zip and delete files. So far I've managed to implement the SwingWorker but it doesn't show and update the TextArea. The results are only shown in the console. Could someone tell me with an example what I am doing wrong or what am I missing? The code I've made is the shown below:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.zip.*;
import javax.swing.*;
import java.util.List;
#SuppressWarnings("serial")
public class zipfiles2 extends JFrame {
static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private File datei, parent;
private String name;
class Task extends SwingWorker<String, String>
{
String status;
JTextArea statusprocess;
public Task(JTextArea statusprocess)
{
this.statusprocess = statusprocess;
}
private String addToZip(String path, String srcFile, ZipOutputStream zipOut) throws IOException
{
File file = new File(srcFile);
String filePath = "".equals(path) ? file.getName() : path + "/" + file.getName();
if (file.isDirectory())
{
for (String fileName : file.list())
{
status = "Folder: "+srcFile + "/" +" is being added to the zip file";
addToZip(filePath, srcFile + "/" + fileName, zipOut);
}
}
else
{
if (new File(filePath).canRead())
{
status = "File "+filePath+"is being zipped";
}
else
{
status = "File: "+filePath+" is being zipped";
zipOut.putNextEntry(new ZipEntry(filePath));
FileInputStream in = null;
try {
in = new FileInputStream(srcFile);
} catch (FileNotFoundException e) {
new File(srcFile).delete();
}
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int len;
while ((len = in.read(buffer)) != -1) {
zipOut.write(buffer, 0, len);
}
in.close();
}
}
return status;
}
public String zipFile(String fileToZip, String zipFile, boolean excludeContainingFolder) throws IOException
{
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
File srcFile = new File(fileToZip);
if(excludeContainingFolder && srcFile.isDirectory())
{
for(String fileName : srcFile.list())
{
addToZip("", fileToZip + "/" + fileName, zipOut);
}
}
else
{
addToZip("", fileToZip, zipOut);
}
zipOut.flush();
zipOut.close();
status = "The zip file " + zipFile + " was created successfully";
return status;
}
public String deleteDirectory(File f) throws IOException {
if (f.isDirectory()) {
for (File c: f.listFiles()) {
status= "File: "+c.getName()+" is being deleted";
deleteDirectory(c);
}
f.delete();
}
else
{
f.delete();
}
return status;
}
#Override
protected String doInBackground() throws Exception {
zipFile(datei.getAbsolutePath(), parent.getAbsolutePath()+"/"+name, true);
publish(status);
deleteDirectory(datei);
publish(status);
return status;
}
#Override
protected void process(List<String> chunks)
{
for (String status : chunks) {
statusprocess.append(status);
}
}
}
public zipfiles2() {
JFileChooser browser = new JFileChooser();
browser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
JPanel panel = new JPanel();
final JTextArea showprogress = new JTextArea();
ActionListener fileValidation = new ActionListener()
{
public void actionPerformed(ActionEvent actionEvent)
{
JFileChooser browser2 = (JFileChooser) actionEvent.getSource();
String command = actionEvent.getActionCommand();
if (command.equals(JFileChooser.APPROVE_SELECTION))
{
datei = browser2.getSelectedFile();
parent = browser2.getCurrentDirectory();
File[] dio = parent.listFiles();
if (datei.isFile()) { name = datei.getName().substring(0, datei.getName().lastIndexOf("."))+".zip"; }
else { name = datei.getName()+".zip"; }
for (File dateien: dio)
{
if (dateien.isFile() && dateien.getName().endsWith(".zip"))
{
if (name.equals(dateien.getName()))
{
JOptionPane.showMessageDialog(null,"Eine Zip-Datei mit der Name der ausgewählten Datei existiert bereits im Ordner", "Validierung", JOptionPane.WARNING_MESSAGE);
new zipfiles2().setVisible(true);
}
}
}
Task task = new Task(showprogress);
task.execute();
}
else
{
System.exit(0);
}
}
};
browser.addActionListener(fileValidation);
JProgressBar progessbar = new JProgressBar();
progressbar.setIndeterminate(true);
panel.add(progressbar);
panel.add(showprogress);
Dimension ScS = Toolkit.getDefaultToolkit().getScreenSize();
this.setTitle("Zip Tool");
this.setSize(200, 90);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocation(ScS.width/2 - this.getSize().width/2, ScS.height/2 - this.getSize().height/2);
browser.showOpenDialog(this);
this.add(panel, BorderLayout.PAGE_START);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try
{
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
}
catch (Exception ex)
{
ex.printStackTrace();
}
new zipfiles2().setVisible(true);
}
});
}
}
EDIT: The code above is a new version, with the corrections suggested. However, it doesn't show my GUI yet. Am I still missing something?
SECOND EDIT: My GUI is shown but my textarea is not being updated. How should I pass the statuses from the other methods to the doInBackground method in order to publish? Maybe an ArrayList type String?
You are not correctly overriding the process method , the signature is like :
protected void process(List<V> chunks)
in your case it would be :
protected void process(List<String> chunks)
Using the #Override annotation would have prevented this problem .
Then, you would use it that way :
#Override
protected void process(List<String> chunks) {
for (String status : chunks) {
statusprocess.append(status);
}
}

Related Links

Running debian packages in Scala
Java Button Full Screen
mySQL Subquery to Stored Procedure or JPA query
How to return SeekBar value to previous activity?
Special Characters with MYSQL JAVA Netbeans and JXL
Unable to get this method to work [closed]
How to extract an email address which is not in a regular expression format from a span text using selenium web driver?
Spring boot health check on existing webapp
How to optimise java pattern replace
How to authenticate with rest webservice using oauth2
Starting ActiveMQ with Stomp
Customized selenium Output
Sending a large data by Post between servlets [duplicate]
Fetching the CA details from a x.509 certificate in Android
java - unique list of different objects with same fields (id, name, …)
Suite for pages in Fitnesse Java

Categories

HOME
twitter
atom-editor
gerrit
debugging
amazon-ec2
keras
drivers
kde
cmd
webpack-2
ebean
adfs
elasticsearch-hadoop
primary-key
adobe-analytics
node-pdfkit
izpack
task
nodatime
object-detection
accessor
captiveportal
crystal-reports-2010
brunch
pingfederate
neo4j-spatial
assistant
wtx
atlassian-crucible
microsoft-chart-controls
yadcf
preg-match-all
mozilla
atl
wixsharp
devextreme
webdriver-manager
acoustics
reactive-cocoa-5
babel-core
taffy
network-flow
jquery-nestable
celery-task
pg-dump
redundancy
pycaffe
vmware-tools
radtreelist
ado.net-entity-data-model
thrust
etsy
react-native-listview
qgraphicsview
dataview
asp.net5
independentsoft
rgeo
responsive-images
service-accounts
cisco-ios
angular-local-storage
bridge.net
google-style-guide
javafx-webengine
codeigniter-routing
client-side-templating
zend-route
xojo
uitouch
rebol3
resty-gwt
ember-charts
meteor-velocity
mcts
xsockets.net
jmapviewer
listings
lcs
clipper
angularjs-controller
dice
amazon-appstore
gnustep
oncheckedchanged
modelstate
forums
audio-capture
boost-smart-ptr
signal-handling
ajax-forms

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App