ProgressMonitor problem
hi,
I have small problem with ProgressMonitor. This is how I create it:
progressMonitor = new ProgressMonitor(guiPool.getMainFrame(), message, note, 0, mediaIds.size());
progressMonitor.setProgress(0);
progressMonitor.setMillisToPopup(100);
progressMonitor.setMillisToDecideToPopup(100);
mediaIds.size() can be:
- > 100
- > 1000
- > 10000
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
progressMonitor.setProgress(0);
progressMonitor.setNote(synchronizedMessage + " 0%");
Than I do somenthing and refresh the progress monitor:
for(...) {
// do something
// refresh preogress monitor
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
progressMonitor.setProgress(tmpCount);
progressMonitor.setNote(tmpNote);
My loops has more than > 2000 cycles. If for i.e. mediaIds.size() hat 3400 elements, than my progress monitor will be show if it reached about 1% of the progress. Why is it so? How can I show my progress monitor from the beginning?
Best Regards,
Rafal
Okay, so I looked at the demo, then said to myself...
What if I built my own ProgressMonitor that does all the things I want ?
After all what is it comprised of ...
Well the main component is a javax.swing.JProgressBar...
So I could create a JDialog window with a JProgressBar
and maybe add...
like a button, maybe a couple labels, some icons or even an image...
of course there is a little work that need to be done as far as updated the progress bar,
but then I have "full" control on when, how, the starting position and and by what increments I want it to display the progress...
And the cool part, is it that I can have the JDialog behave the way I want it to also...
Like make it non-closable until the cancel button is pressed or task is complete...
This maybe a possible solution for you problem...
Information for how to do this in the same place ( not the page ) your link points to...
The Java Tutorial: Lesson : How to Use Progress Bars
http://java.sun.com/docs/books/tutorial/uiswing/components/progress.html
remember, there are many ways to solve a problem...
- MaxxDmg...
- ' He who never sleeps... '
Similar Messages
-
Problem with threads and ProgressMonitor
Dear Friends:
I have a little problem with a thread and a ProgressMonitor. I have a long time process that runs in a thread (the thread is in an separate class). The thread has a ProgressMonitor that works fine and shows the tasks progress.
But I need deactivate the main class(the main class is the user interface) until the thread ends.
I use something like this:
LongTask myTask=new LongTask();
myTask.start();
myTask.join();
Now, the main class waits for the task to end, but the progress monitor don`t works fine: it shows only the dialog but not the progress bar.
What's wrong?Is the dialog a modal dialog? This can block other UI updates.
In general, you should make sure that it isn't modal, and that your workThread has a fairly low priority so that the UI can do its updating -
Problem with painting/threads/ProgressMonitor
Hello,
I'll try to be clear, ask me anything if it isn't. I have two threads, one that downloads some selected webpages, and the other that reads them. In the thread that reads, there is a ProgressMonitor object, which indicate how many webpages have been read.
I created a JUnit test which works as expected. One thread downloads, the other reads and a nice little progress monitor appears and everything works.
I transfered the code (the part of the code starting the thread that reads, which starts the thread that downloads) into the main application. The threads are working and the ProgressMonitor appears, but it does not draw the components (there is no label, progress bar, button etc...). I can't seem to find the problem. I think it is caused by the threads or synchronized methods, I am not sure as I am no expert with threads. Once the threads have finished running, the components of the ProgressMonitor appears. So I guess that the threads are blocking the (re)painting of the application, but I can't figure why. Im using Thread.yield() quite often. Priorities problem ? Here some parts of the code :
JUnit Test code :
public synchronized void testHarvest() {
JFrame frame = new JFrame("Super");
frame.setVisible(true);
Harvester harvester = new Harvester(
frame,
new Rule());
Thread harvest = new Thread(harvester);
harvest.start();
try {
harvest.join();
} catch (InterruptedException ie) {}
...Main application :
Code:
public class Gui extends JFrame implements ComponentListener {
private static JFrame mMotherFrame = null;
public Gui() {
mMotherFrame = this;
private class GuiActionRealize {
public synchronized void getFromWeb() {
Harvester harvester = new Harvester(
mMotherFrame,
new Rule());
Thread harvest = new Thread(harvester);
harvest.start();
try {
harvest.join();
} catch (InterruptedException ie) {}
}Harvester :
Code:
public class Harvester implements Runnable {
private JFrame mMotherFrame;
private ProgressMonitor mMonitor;
public Harvester(JFrame owner, IRule subjectRule) {
mMotherFrame = owner;
public void find() {
mMonitor = new ProgressMonitor(mMotherFrame, "Downloading from the Internet.", "", 1, mAcceptedURLs.size());
mMonitor.setMillisToDecideToPopup(0);
mMonitor.setMillisToPopup(0);
public void run() {
find();
mHarvested = harvest();
mFinished = true;
Thread.yield();
public List harvest() {
download = new DownloadThread(this, mAcceptedURLs);
Thread downthread = new Thread(download);
downthread.start(); int i = 0;
while (!mMonitor.isCanceled()) {
while (download.getDownloadedDocuments().isEmpty()) {
try {
Thread.yield();
Thread.sleep(300);
} catch (InterruptedException ie) {}
mMonitor.setNote("Downloading decision " + i);
mMonitor.setProgress(mMonitor.getMinimum()+ ++i);
} // end while(!cancel)
download.kill();
return mHarvested;
}I'm very puzzled by the fact that it worked in the JUnit Case and not in the application.
I can see that the thread that is responsible for drawing components is not doing his job, since that the mother frame (Gui class) is not being repainted while the harvest/download threads are working. That's not the case in the JUnit case, where the frame is being repainted and everything is fine. This is the only place in the application that I'm using threads/runnable objects.
I also tried making the Gui class a thread by implementing the Runnable interface, and creating the run method with only a repaint() statement.
And I tried setting the priority of the harvest thread to the minimum. No luck.
If you need more info/code, let me know, Ill try to give as much info as I can.
Thank youWhy are you painting the values yourself? Why don't you just add the selected values to a JList, or create a container with a GridLayout and add a JLabel with the new text to the container.
Every time you call the paintComponent() method the painting gets done from scratch so you would need to keep a List of selected items and repaint each item every time. Maybe this [url http://forum.java.sun.com/thread.jsp?forum=57&thread=304939]example will give you ideas. -
Delicate ProgressMonitor/ event handling problem
Hi,
I have a delicate ProgressMonitor / event handling problem.
There exists some solution on similiar problems here in the forums, but no solution to my special problem, hope anybody can help me out.
I have a rather big project, an applet, that I've written a separate JarLoader class that will load specific jar's if the ClassLoader encounter a unloaded class, all ok so far.
But, during loading, I would like to display a ProgressBar. And here is the problem. If my custom ClassLoader intercepts a findClass -request that needs to load the class from a jar from a normal thread, this is no problem, but if the ClassLoader intercepts a findClass that needs loading a jar when inside the EventQueue -thread, this is becomming tricky!
The catch is that an event posted on the EventQueue finally needs a class that needs to be loaded, but I cannot dispatch a thread to do this and end that particular event before the class itself is loaded.
So how do I hold the current EventQueue -event needing a jar -load, Pop up a ProgressBar, then process events in the EventQueue to display the ProgressBar and update repaints in it? then return from the event that now have loaded needed class-files.
I've tried a tip described earlier in the forums by trying to handle events with this code when loading the Jar:
/** process any waiting events - use during long operations
* to update UI */
static public void doEvents() {
// need to derive from EventQueue otherwise
// don't have access to protected method dispatchEvent()
class EvtQueue extends java.awt.EventQueue {
public void doEvents() {
Toolkit toolKit = Toolkit.getDefaultToolkit();
EventQueue evtQueue = toolKit.getSystemEventQueue();
// loop whilst there are events to process
while (evtQueue.peekEvent() != null) {
try {
// if there are then get the event
AWTEvent evt = evtQueue.getNextEvent();
// and dispatch it
super.dispatchEvent(evt);
catch (java.lang.InterruptedException e) {
// if we get an exception in getNextEvent()
// do nothing
// create an instance of our new class
EvtQueue evtQueue = new EvtQueue();
// and call the doEvents method to process the events.
evtQueue.doEvents();
}Then, the loader checks
java.awt.EventQueue.isDispatchThread()to see if its' inside the eventqueue, and runs doEvents after updating the ProgressMonitor with new setProgress and setNote values.
More precise;
The loader is loading the jar like this:
(this is pseudo code, not really usable, but outlines the vital parts)
public void load() {
monitor = new ProgressMonitor(null, "Loading " + jarName, ""+jarSize + " bytes", 0, jarSize);
monitor.setMillisToDecideToPopup(0);
monitor.setMillisToPopup(0);
// reading jar info code here ...
JarEntry zip = input.getNextJarEntry();
for (;zip != null;) {
// misc file handling here... total = current bytes read
monitor.setProgress(total);
monitor.setNote(note);
if (java.awt.EventQueue.isDispatchThread()) {
doEvents();
zip = input.getNextJarEntry();
monitor.close();
}When debugging doEvents(), there is never any events pending in peekEvents(), even if I tries to put a invokeLater() to run the setProgress on the monitor, why? If it had worked, the doEvents() code would have saved my day...
So, this is where I'm totally stuck...Just want to describe how I did this using spin from http://spin.sourceforge.net
This example is not pretty, but it can probably help others understanding spin. Cancelling the ProgressMonitor is not implemented, but can easily be done by checking on ProgressMonitor.isCanceled() in
the implementation code.
First, I create a bean for displaying and run a ProgressMonitor:
Spin requires an Interface and an Implementation, but that's just nice programming practice :-)
import java.util.*;
public interface ProgressMonitorBean {
public void start(); // start spinning
public void cancel(); // cancel
public int getProgress(); // get the current progress value
public void setProgress(int progress); // set progress value
public void addObserver(Observer observer); // observer on the progressValue
}Then, I created the implementation:
import java.util.*;
import javax.swing.ProgressMonitor;
import java.awt.*;
public class ProgressMonitorBeanImpl extends Observable implements ProgressMonitorBean {
private ProgressMonitor monitor;
private boolean cancelled;
private int progress = 0;
private int currentprogress = 0;
public ProgressMonitorBeanImpl(Component parent, Object message, String note, int min, int max) {
monitor = new ProgressMonitor(parent, message, note, min, max);
monitor.setMillisToDecideToPopup(0);
monitor.setMillisToPopup(0);
public void cancel() {
monitor.close();
public void start() {
cancelled = false;
progress = 0;
currentprogress = 0;
while (progress < m_cMonitor.getMaximum()) {
try {
synchronized (this) {
wait(50); // Spinning with 50 ms delay
if (progress != currentprogress) { // change only when different from previous value
setChanged();
notifyObservers(new Integer(progress));
monitor.setProgress(progress);
currentprogress = progress;
} catch (InterruptedException ex) {
// ignore
if (cancelled) {
break;
public int getProgress() {
return progress;
public void setProgress(int progress) {
this.progress = progress;
}in my class/jarloader code, something like this is done:
public void load() {
ProgressMonitorBean monitor = (ProgressMonitorBean)Spin.off(new ProgressMonitorBeanImpl(null, "Loading " + url,"", 0, jarSize));
Thread t = new Thread() {
public void run() {
JarEntry zip = input.getNextJarEntry();
for (;zip != null;) {
// misc file handling here... progress = current bytes read
monitor.setProgress(progress);
t.start(); // fire off loadin into own thread to do time consuming work
monitor.start(); // this will spin events on monitor and block until progress = max
monitor.cancel(); // Just make sure ProgressMonitor is closed
}The beautiful thing here is that Spin is taking care of weither the load() is inside the dispatch thread or not, making the code much simpler and cleaner to understand.
The ProgressMonitorBeanImplementation could been made much nicer and more complete, but I was in a hurry to check if it worked out. And it did! This will be applied on a lot of gui -components that blocks the event-queue in our project, making it much more responsive.
Hope this will help others in similiar situations! Thanks again svenmeier for pointing me to the spin -project. -
Problem with JTimer and ProgressMonitor
Hi,
I am developing an JApplet which reads data from database and displays, for this i am using applet servlet communication, now depending upon the intranet speed and file size the time for getting the data varies, so I have to show a the user the process is going on, now i went through this article
http://java.sun.com/docs/books/tutorial/uiswing/components/progress.html
I modified some code for my use but it does not work i will cut paste it down here
Can anyone help me in doing it the right way. should i use JProgressBar instead of ProgressMonitor. is so how???
//c is the content pane of my applet
ProgressMonitor pMonitor = new ProgressMonitor( c, "Getting Data...", "Note", 0, 100 );
pMonitor.setProgress( 0 );
pMonitor.setMillisToDecideToPopup( 0 );
pMonitor.setMillisToPopup( 2);
pMonitor.setMaximum( 20000 );
timer = new javax.swing.Timer( 100, new TimerListener() );
counter = 0;
timer.start();
// this is the method where i get all the data from database
getAllData();
timer.stop();
public class TimerListener implements ActionListener
public void actionPerformed( ActionEvent e )
counter = counter + 1;
pMonitor.setProgress( counter );
AshishIs the dialog a modal dialog? This can block other UI updates.
In general, you should make sure that it isn't modal, and that your workThread has a fairly low priority so that the UI can do its updating -
Hi!
I wanted to create a ProgressMonitor and display it to show that a task is still being executed. Unfortunately, the ProgressMonitor does not show.
public void initializeProgressMonitor()
_pm = new ProgressMonitor(_parent, "SNPs werden exportiert", "Hurra", 0, 100);
_pm.setMillisToPopup(0);
System.out.println("PM visible");
_pm.setProgress(0);
_pm.setMillisToPopup(2);
_pm.setMillisToDecideToPopup(2);
* @see javax.swing.SwingWorker#doInBackground()
@Override
protected Void doInBackground() throws SQLException
try
importIDs();
_pm.setNote(IDs were imported.");
exportFile();
catch (Exception e)
new ExceptionFrame(e, null, true);
ErrorHandler.logError(e);
return null;
}Thanks for any advice!Nevermind! Obviously ProgressMonitor is not the best choice to display an indeterminate progress, because I only had to use setProgress and then it appeared.
-
How can i get ProgressMonitor to display while task is going on.
hi can anybody tell me what i'm doing wrong.. I don't understand threads that well. I'm writing ftp client that uploads user files to our ftp.server. My problem is ProgressMonitor hangs until ftp transfer is done before displaying message of the job status... I try to give it it's own thread. but it seems like the process for ftp upload takes higher priority so ProgressMonitor does not get attention til all ftp process is done...
import java.io.*;
import java.util.List;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import sun.net.ftp.*;
import sun.net.*;
* An application that displays a ProgressMonitor
* when the 'Upload' button is pressed. A complex
* 'operation' to upload files and update the monitor
* @author
public class ProgressTestApp extends JApplet {
private JPanel actionPanel;
private String names[] = { "browse..","Upload" };
private JButton choices[];
private JLabel label;
private JTextField FolderpathText;
private JPanel reportPanel;
private String newline = "\n";
private JTextArea taskOutput;
private File pwFile;
private ProgressMonitor monitor;
private String fullpath;
private List mylist;
Thread thread = new Thread();
JFrame frame = new JFrame( "Progress-Monitor" );
private int mini=0;
public int maxi=100;
public int boo=0;
private Runnable runnable;
/** a lable for the lient info text **/
private JLabel getclientLabel()
if ( label == null )
label = new JLabel("Directory to upload: ") ;
return label;
/** a text to show client info */
private JTextField getFolderpathText()
if ( FolderpathText == null)
FolderpathText = new JTextField (100);
FolderpathText.setText( " " );
return FolderpathText;
/** a text to show client info */
private JTextArea gettaskOutput()
if ( taskOutput == null)
taskOutput = new JTextArea(5, 20);
taskOutput.setMargin(new Insets(5,5,5,5));
taskOutput.setEditable(false);
return taskOutput;
private JPanel getreportPanel()
if (reportPanel == null)
reportPanel = new JPanel(new BorderLayout());
reportPanel.add(getclientLabel(),BorderLayout.WEST);
reportPanel.add(getFolderpathText(),BorderLayout.CENTER);
return reportPanel;
* Application entry point.
* Create the splash window, and display it.
* @param args Command line parameter. Not used.
public void init() {
// Create a frame with a single button in it.
// When the button is pressed, a thread is spawned
// to run out sample operation.
//JFrame frame = new JFrame( "ProgressMonitor Test" );
//create array of buttons
choices = new JButton[names.length];
//set up panel for buttons
actionPanel = new JPanel();
actionPanel.setLayout( new GridLayout(1,choices.length));
//set up buttons and register their listeners
for ( int count = 0; count < choices.length; count++ )
choices[count]=new JButton(names[count]);
actionPanel.add(choices[count]);
Container container = getContentPane();
container.setBackground(Color.gray);
container.add( getreportPanel(), BorderLayout.NORTH);
container.add( actionPanel, BorderLayout.CENTER);
// Create a ProgressMonitor. This will be started
// when the Upload button is pressed.
int min = mini;
int max = maxi;
String[] message = new String[2];
message[0] = "Performing Operation.";
message[1] = "This may take some time...";
final ProgressMonitor monitor = new ProgressMonitor( frame,
message,
" of ",
min,
max );
// This is our sample operation.
final Runnable runnable = new Runnable() {
public void run() {
if( boo == 1 )
maxi=file_utility(pwFile);
int sleepTime = 1000;
for( int i = 1; i < maxi; i++ ) {
try {
monitor.setNote( i + " of " + maxi );
monitor.setProgress( i ); monitor.setMinimum( i ); monitor.setMaximum( maxi );
if( monitor.isCanceled() ) {
monitor.setProgress( maxi );
break;
Thread.sleep( sleepTime );
catch( InterruptedException dontcare ) {
monitor.close();
choices[0].addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event ) {
// Run the operation in its own thread.
pwFile=findfile();
FolderpathText.setText(pwFile.getAbsolutePath());
boo=1;
choices[1].addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event ) {
// Run the operation in its own thread.
Thread thread = new Thread( runnable );
thread.start();
ftp_utility(pwFile);
} // main
/*** Folder locater to find local file to upload ***/
File findfile()
JFileChooser myFC = new JFileChooser();
myFC.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = myFC.showOpenDialog(new JFrame());
if(returnVal == JFileChooser.APPROVE_OPTION)
//JOptionPane.showMessageDialog( null, myFC.getSelectedFile());
File file = myFC.getSelectedFile();
//String fullpath=c.getSelectedFile().getName();
return file;
/***Fi_l_e_s to upload ***/
public int file_utility (File uploadFile)
int files=0;
FtpClient fcMyFtp = new FtpClient();
try
int ch;
fcMyFtp.openServer("ftp.abc.com");
fcMyFtp.login("Anonymous","[email protected]");
fcMyFtp.binary();
fcMyFtp.cd("incoming40");
if( uploadFile.isDirectory())
if( mylist == null )
mylist= Arrays.asList(uploadFile.list());
catch (Exception exception)
JOptionPane.showMessageDialog(null,exception);
return mylist.size();
/***FT_P _ ***/
public void ftp_utility (File uploadFile)
FtpClient fcMyFtp = new FtpClient();
try
int ch;
fcMyFtp.openServer("ftp.abc.com");
fcMyFtp.login("Anonymous","[email protected]");
fcMyFtp.binary();
fcMyFtp.cd("incoming40");
if( uploadFile.isDirectory())
if( mylist == null )
mylist= Arrays.asList(uploadFile.list());
for(int count=0; count < mylist.size(); count++)
fullpath=uploadFile.getAbsolutePath()+"\\"+mylist.get(count);
File file = new File(fullpath);
if( file.isDirectory())
//file.mkdir();
//ftp_utility(file);
else
TelnetOutputStream out = fcMyFtp.put(file.getName());
FileInputStream in = new FileInputStream(file);
int c = 0;
while ((c = in.read()) != -1 )
out.write(c);
in.close();
out.close();
fcMyFtp.closeServer();
//JOptionPane.showMessageDialog( null, "Upload completed...");
catch (Exception exception)
JOptionPane.showMessageDialog(null,exception);
} // ProgressTestFirst of all, please use the code tags when posting code, especially that much code. http://forum.java.sun.com/faq.jsp#messageformat
The problem is that you need to switch the threads, so you should spawn the ftp process in a new thread, and let the monitor run in the main thread (actually the UI thread). I don't think that's really documented anywhere. I had the same problem the first time. -
How to find out which BR that is the problem when running CmdLnLauncher.bat
Hi there
Trying to run a sequence using CmdLnLauncer, and it starts great. It starte calculating but then throws this error.
"2012-09-04 15:21:24,790 FATAL main com.hyperion.hbr.cmdlnlauncher.ProgressMonito
r - Exception:
Execution ended with error.
Error Code: EXE002
Error Args: [Ljava.lang.Object;@2f0d54
ClassName: com.hyperion.hbr.excp.ExecutionException
Exception (1200497): Error parsing formula for [FIX STATEMENT] (line 16): unknow
n member name [@_NULL] in function [@IDESCENDANTS]
ClassName: java.lang.Exception
2012-09-04 15:21:24,790 WARN main com.hyperion.hbr.cmdlnlauncher.ProgressMonitor
- Execution ended with error."
How do I figure out which BR is the problem? I can't seem to find the rule it is refering to, as theHave a search for hbrlaunch.log as it might hold the answer, location can depend on version and OS
or another option to enable business rule auditing in Planning and then check the HSP_AUDIT_RECORDS table
Cheers
John
http://john-goodwin.blogspot.com/ -
How to disable the cancel button in the ProgressMonitor
hi,
I need to know, is there any way to disable/remove the (cancel)button in the ProgressMonitor?
One more problem is,
Once i click the cancel button, isCanceled() return true, how to make it false again so that the process continue....
It is very urgently.....
please help me out.
Thanks in advance.
Regards,
Deepa RaghuramanI don't think that's a good solution, because Cancel button itself is not disabled, so user is tempted to click it and nothing happens.
A better but dangerous solution is this:
progressMonitor = new ProgressMonitor(ProgressMonitorDemo.this,
"Running a Long Task",
"", 0, 100);
progressMonitor.setMillisToDecideToPopup(0);
progressMonitor.setMillisToPopup(0);
progressMonitor.setProgress(0);
JDialog dialog = (JDialog)progressMonitor.getAccessibleContext().getAccessibleParent();
JOptionPane pane = (JOptionPane)dialog.getContentPane().getComponent(0);
pane.setOptions(new Object[]{});Refer to the same question here [http://stackoverflow.com/questions/512151/how-do-i-disable-the-cancel-button-when-using-javax-swing-progressmonitor] . -
ProgressMonitor dialog will not popup
Can anybody tell me what's wrong with the following code? The ProgressMonitor dialog never pops up.
class OkListener implements ActionListener
public void actionPerformed(ActionEvent ae)
Runnable task = new Runnable()
public void run()
String login = _getJTFLogin().getText();
String pwd = new String(_getJTFPassword().getPassword());
ProgressMonitor progMon = new ProgressMonitor(_parent, "Please wait...", "Authentification", 0, 100);
progMon.setProgress(0);
progMon.setMillisToDecideToPopup(1000);
try
doAuthentification(login, pwd);
catch (Exception exc)
exc.printStackTrace();
finally
progMon.close();
Thread worker = new Thread(task);
worker.start();
And, somehow, if I add a fake Thread.sleep() call and a progMon.setProgress(50) after the doAuthentification() method, the dialog pops up.
Any logic to this? I have read the documentation but nothing seems to explain this behavior.
Thanks a lot!
GuillaumeFrom mentioning the DIALOGEX, it sounds like you've read one of my many posts on the subject (or figured it out for yourself). An easy may to see if that's the still the problem is when the dialog doesn't show up, it should act like there's a modal dialog you just can't see. I.e., you can't click on AI's menus, panels or the document. If that's the case but when you hit ESC it acts like the invisible dialog has disappeared, it's probably still the DIALOGEX thing in some way. I might have a suggestion or two on that score if that's the case.
Code-wise though, you look fine. So I always strongly lean towards that stupid DIALOGEX problem. -
Progress of Zipping of folder on ProgressMonitor??
Hi all friends,
I am facing problem with showing the progress of zipping of folder for that Iam using ProgressMonitor.I am really confused what will be the code for that I have tried with my below codes but couldn't slove my problem.My below codes zipping folder successfully only problem with showing the progress of zipping on ProgressMonitor.Can any one please rectify me where iam wrong.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.zip.*;
public class ZipUtility1
{ ZipOutputStream cpZipOutputStream = null;
String strSource = "";
String strTarget = "";
String strSubstring = "";
public static void main(String[] args) {
if( args == null || args.length < 2) {
System.out.println("Usage: java ZipUtility <directory or file to be zipped> <name of zip file to be created>");
return;
ZipUtility1 udZipUtility = new ZipUtility1();
udZipUtility.strSource = args[0];
udZipUtility.strTarget = args[1];
udZipUtility.zip();
private void zip(){
try {
File cpFile = new File (strSource);
if (!cpFile.isFile() && !cpFile.isDirectory() ){
System.out.println("\nSource file/directory Not Found!");
return;
if (cpFile.isDirectory()) {
strSubstring = strSource;
} else {
strSubstring = "";
cpZipOutputStream = new ZipOutputStream(new FileOutputStream(strTarget));
cpZipOutputStream.setLevel(9);
zipFiles(cpFile,null);
cpZipOutputStream.finish();
cpZipOutputStream.close();
JOptionPane.showMessageDialog( null, "ZIPING COMPLETE");
System.out.println("\n Finished creating zip file " + strTarget + " from source" + strSource);
}catch (Exception e){
e.printStackTrace();
//Method of Zipping
private void zipFiles(File cpFile,Component parentComponent) {
int size=(int)cpFile.length();
//ProgressMonitor intialization
ProgressMonitor monitor = new ProgressMonitor(parentComponent,"Packing " + strSource + "...", "", 0,size);
monitor.setMillisToDecideToPopup(0);
monitor.setMillisToPopup(0);
if (cpFile.isDirectory()) {
File fList[] = cpFile.listFiles();
for (int i=0; i< fList.length; i++){
zipFiles(fList,null);
else {
try {
String strAbsPath = cpFile.getAbsolutePath();
String strZipEntryName ="";
if (!strSubstring.equals("") ){
strZipEntryName = strAbsPath.substring(strSource.length()+1,strAbsPath.length());
} else {
strZipEntryName = cpFile.getName();
byte[] buf = new byte[16384];
FileInputStream cpFileInputStream = new FileInputStream (cpFile) ;
ZipEntry cpZipEntry = new ZipEntry(strZipEntryName);
cpZipOutputStream.putNextEntry(cpZipEntry );
//ProgressMonitor setNote
monitor.setNote(cpZipEntry.getName());
int len;
int count=0;
while ((len = cpFileInputStream.read(buf)) > 0)
cpZipOutputStream.write(buf, 0, len);
count += len;
monitor.setProgress(count); //ProgressMonitor setProgress
cpZipOutputStream.closeEntry() ;
} catch (Exception e) {
e.printStackTrace();
}//End of Zipping Method
}//End of class
Regards
BikashDon't you think that the ProgressMonitor needs to run on a separate thread than your Zip utility. This thread would query results from the thread running Zip utility and repaint.
-
Hi guys. I have a problem with ProgressMonitor, I already read the tutorial implements an example (that works well but when I try to apply the ProgressMonitor to my program is not work. I don't no what to do, I don't have another ways to fix this problem. Maybe you can help me!!!
I have a task that consist to apply filters in files (i.e., get just data that "pass" to a determinate restriction), the code look likes:
progress = new ProgressMonitor(null, "Filtros", "", 0, filters.size()); //create the progress menu
//for each filter
for(int filterCount = 0; filterCount < filters.size(); filterCount++)
progress.setProgress(filterCount);
if(progress.isCanceled())
progress.close();
return;
try{
Thread.sleep(1000);
}//End try
catch(InterruptedException ie)
}//End for - filterWhen I execute the program I don't see the progress bar, it just appear at the end of operations, i.e. just appear the last filter!?!? Why I doing wrong?!?!
Thanks.
GiscardHi guys, I am here again!!!!!
I do some tests and get some information. My ProgressMonitor just works when I use a text application, for example:
public class TestProgress{
publis static void main(String args[]){
ProgressMonitor progress = new ProgressMonitor(null, "Teste", "", 0, 100);
progress.setMillisToDecideToPopup(500);
progress.setMillisToPopup(1000);
progress.setProgress(0);
for(int i = 0; i < 100; i++)
progress.setProgress(i);
progress.setNote("TEST" + i);
System.out.println("" + i);
if(progress.isCanceled())
break;
try{Thread.sleep(1000);}
catch(InterruptedException ie){}
}//End for
progress.close();
}//End main()
}//End classIf the application use a JInternalFrame swing, it doesn't work, I test the application use only JFrame, and it works, but when I have a JFrame with swing inside, it doen't work.
Someone knows what?!!? Thanks
Giscard -
ProgressMonitor progressMonitor = new ProgressMonitor(mviewer,
"Running a Long Task",
"", 0, 100);
progressMonitor.setProgress(0);
progressMonitor.setMillisToDecideToPopup(0);
int i;
i = 1000;
while(i>0){
i--;
progressMonitor.setNote(null);
progressMonitor.setProgress(i);
I have added the above code to my program where mviewer is a JFrame.
however, i can't see the ProgressMonitor to pop up.
what is my problem?
thxWhen you call setProgress(i), if i>MAXIMUM, progressMonitor will be closed automatically. Here your MAXIMUM=100, but i=1000.
-
ProgressMonitor not showing properly
Sorry for cross-posting, but in general Java programming, nobody seems to have any idea. The original thread is http://forum.java.sun.com/thread.jsp?forum=31&thread=319651
Here's what it's about:
I've got a little prob using ProgressMonitor. I'm coding an Applet which loads some images. Since this task may take a while, I'm trying to use ProgressMonitor to show a dialog window with the corresponding progressbar to indicate how much work's done already.
My code looks like this:
// Image[] images has been filled before.
// mt is a MediaTracker which surveys the loading.
ProgressMonitor pm = new ProgressMonitor(
null,
"Loading images",
0,
images.length - 1
for (int i = 0; i < images.length; i++) {
pm.setProgress(i);
pm.setNote(images[ i ].toString());
// actual image loaded?
while (!mt.checkID(i, true)) {
// if not wait:
Thread.sleep(10);
if (mt.checkAll() && !pm.isCanceled() && !mt.isErrorAny()) {
pm.close();
// everything successfully loadedThe loading of the images works fine. My only prob is with the ProgressMonitor which starts showing after the default time (might be one second) - but the frame it shows is corrupt. You can see the outlines of it, but none of the contents is displayed - not to talk of the progressbar. Simply nothing.
Did anyone encounter this prob as well and has some ideas what's wrong? Any help would be appreciated.
Cheers,
kelysarHi again.
I get the point described in that other thread - but I've got a little problem transferring the solution to my problem. The situation is this:
I've got as class derived from JFrame which shall show thumbnails of some images. In the constructor of that class I call an init()-method in which I'm loading the images to be displayed. I want the ProgressMonitor to survey the loading of the images since that's what is taking most time. In short and pseudo-coded this looks like:
class PicFrame extend JFrame {
public PicFrame() {
// do all initializations, and..
init(); // this shall load the images etc.
pack();
show();
public void init() {
ProgressMonitor pm = new ProgressMonitor(...);
pm.setNote("starting");
pm.setProgress(1);
for (all images specified in an array) {
pm.setProgress(index of current image);
pm.setNote(name of image);
load image with a MediaTracker
if (not cancelled and all images loaded fine) pm.close();
}How am I able to separate the loading of the images into a second thread and update the ProgressMonitor without being blocked by the loading thread?
I'm still chewing on this - so I'd be glad to see any suggestions.
Thanks again for the idea.
cheers,
kelysar -
Using ProgressMonitor for unknown time-consuming task
Hi,
I have a time-conuming task that I don't know how long will it take, and I want to use ProgressMonitor.
I tried to set the maximum to 100 like this:
monitor = new ProgressMonitor(null, "", "", 0, 100);
and then, after the task is finished - to do the following command:
monitor.setProgress(100);
but the progress monitor is never shown.
what is the problem?
thanksPer the API:
A class to monitor the progress of some operation. If it looks like the operation will take a while, a progress dialog will be popped up. When the ProgressMonitor is created it is given a numeric range and a descriptive string. As the operation progresses, call the setProgress method to indicate how far along the [min,max] range the operation is. Initially, there is no ProgressDialog. After the first millisToDecideToPopup milliseconds (default 500) the progress monitor will predict how long the operation will take. If it is longer than millisToPopup (default 2000, 2 seconds) a ProgressDialog will be popped up.
Do you call setProgress at any point?
Maybe you are looking for
-
ENCORE CS6 gives error message during the burning of Blu-ray Disc
I did it again - upgraded my Production Premium CS5 to CS6. I will not forget CS4 that never came to work. It was not a workable version, but at best an Alfa or maybe Beta version. I was therefore naturally afraid to upgrade my reasonably well functi
-
ASR 1002 with SFP GE-T ( Interface not came UP )
Hi Team, e are trying to connect an ASR1002 ( 4XGE-BUILT-IN ) with SFP GE-T to a C3750 Switch but the interface never came up in the ASR and also at Cisco 3750 end. The interfaces are configured in both sides with no negotiation auto and with speed
-
Color correction change across all clips?
I know how to make a color correction to my first clip, then I can copy and paste it onto all the other clips. However, what if I want to change the color correction later on? I have to delete all the color corrected clips, and then make a new correc
-
Neither my shortcuts nor my firefox.exe have Run As Administrator checked. And yet I get this prompt every time I start Firefox on my new laptop with Windows 7 Professional 64-bit.
-
Multiple tc types on one scxi 1102
Does anybody know if you can use two different thermocouple types on one SCXI-1102 module? I need to measure both Type K and Type T thermocouples. I am using a SCXI 1303 connector block and plan to use the internal CJC. Thanks in advance doloop