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

Regex: Match any word that is not the one defined by regex
Cannot go to “chrome://downloads/” in a newly opened tab with Selenium in Chrome
Surprising Exception : Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference
Is H2 database compatible with Oracle 'Insert All' statement?
Android studio :: Unable to see a source folder
Null pointer exception when mapping List in neo4j?
How do I make an Apache Camel Servlet request return immediately?
Java Play Selenium
How to inject database connection factory service into Jersey application
Apache CXF nested complex type creation
Downloading an Image file to my Android App from Amazon S3 using transferutility too slow. Can I speed it up?
Reading a File's Content and then doing analysis upon them
Replace all tags except one with RegExp in Java
Primary key not unique in SQLLite with AutoIncrement
Char array printing random characters
Regex for matching a pokerhand (Java)

Categories

HOME
xamarin
stock
bpmn
mean-stack
tizen-web-app
microservices
youtube-api-v3
podio
google-translate
offline
alignment
orchardcms
uitypeeditor
oxyplot
jasonette
errorlevel
kvc
google-search-api
mustache.php
pass-by-reference
lcd
p-value
intel-pin
dbclient
compatibility
libuv
bcd
yadcf
semantic-versioning
space-complexity
libvpx
c11
xenforo
reportbuilder
hue
email-templates
http-live-streaming
no-www
midl
import-from-excel
wso2carbon
logfiles
menuitem
flickr-api
dds
elgg
font-size
bonobo
pcf
py2app
contact-list
actionbardrawertoggle
rhino-servicebus
independentsoft
wapiti
uid
fouc
wyam
tableau-online
createprocessasuser
generic-programming
mmc
key-management
offloading
clicktag
ng-animate
qpainter
winddk
mdt
socketexception
terminfo
elliptic-curve
system.net.webexception
jsctypes
.aspxauth
dexterity
ruby-datamapper
mylyn
android-screen-support
rdoc
dice
pysimplesoap
nsmanagedobject
joyent
imac
lpeg
blitz++
paster
infrastructure
ncqrs
web-architecture
javap
anti-piracy
geneva-server
wsdl.exe
ntvdm.exe

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App