C++ Read Text From File Show Progress

Sometimes a chore running within a program might take a while to complete. A user-friendly program provides some indication to the user that the task is occurring, how long the task might take, and how much work has already been done. One way of indicating piece of work, and perhaps the amount of progress, is to utilise an animated image.

Another mode of indicating work is to fix the await cursor, using the Cursor class and the Component-defined setCursor method. For example, the following code makes the wait cursor be displayed when the cursor is over container (including whatever components it contains that have no cursor specified):

container.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));          

To convey how complete a task is, you can utilize a progress bar similar this one:

A typical progress bar

Sometimes yous can't immediately make up one's mind the length of a long-running chore, or the task might stay stuck at the aforementioned state of completion for a long time. You can show work without measurable progress by putting the progress bar in indeterminate mode. A progress bar in indeterminate fashion displays animation to signal that work is occurring. Equally soon as the progress bar tin display more meaningful information, you should switch it dorsum into its default, determinate style. In the Java look and experience, indeterminate progress bars look like this:

An indeterminate progress bar

Swing provides three classes to assist y'all utilize progress bars:

JProgressBar
A visible component to graphically brandish how much of a full task has completed. See Using Determinate Progress Bars for information and an instance of using a typical progress bar. The department Using Indeterminate Mode tells you how to animate a progress bar to show activeness before the task's scope is known.
ProgressMonitor
Not a visible component. Instead, an instance of this form monitors the progress of a task and pops upwardly a dialog if necessary. Run across How to Apply Progress Monitors for details and an example of using a progress monitor.
ProgressMonitorInputStream
An input stream with an attached progress monitor, which monitors reading from the stream. You use an instance of this stream similar whatever of the other input streams described in Bones I/O. You can get the stream'due south progress monitor with a phone call to getProgressMonitor and configure information technology as described in How to Use Progress Monitors.

After you meet a progress bar and a progress monitor in activity, Deciding Whether to Use a Progress Bar or a Progress Monitor can help you figure out which is advisable for your awarding.

Using Determinate Progress Bars

Here's a movie of a minor demo application that uses a progress bar to measure the progress of a task that runs in its own thread:

A snapshot of ProgressBarDemo, which uses a progress bar

The following code, from ProgressBarDemo.java, creates and sets upwards the progress bar:

            //Where member variables are declared:            JProgressBar progressBar; ...            //Where the GUI is constructed:            progressBar = new JProgressBar(0, chore.getLengthOfTask()); progressBar.setValue(0); progressBar.setStringPainted(truthful);          

The constructor that creates the progress bar sets the progress bar's minimum and maximum values. You tin also gear up these values with setMinimum and setMaximum. The minimum and maximum values used in this program are 0 and the length of the job, which is typical of many programs and tasks. Withal, a progress bar's minimum and maximum values tin can be any value, even negative. The code snippet also sets the progress bar's current value to 0.

The call to setStringPainted causes the progress bar to brandish, within its bounds, a textual indication of the percentage of the job that has completed. By default, the progress bar displays the value returned by its getPercentComplete method formatted as a per centum, such as 33%. Alternatively, y'all tin can replace the default with a different string by calling setString. For example,

if (/*...half style washed...*/)     progressBar.setString("Half style there!");          

When the user clicks Starting time, an case of the inner class Task is created and executed.

public void actionPerformed(ActionEvent evt) {     startButton.setEnabled(false);     setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));     washed = simulated;            task = new Chore();     chore.addPropertyChangeListener(this);     task.execute();            }          

Task is a subclass of javax.swing.SwingWorker. The Task instance does three important things for ProgressBarDemo:

  1. The example invokes the doInBackground in a carve up thread. This is where the long-running task is actually executed. Using a background thread instead of the event-dispatching thread prevents the user interface from freezing while the task is running.
  2. When the background chore is complete, the instance invokes the done method in the event-dispatching thread.
  3. The example maintains a bound belongings, progress, that is updated to point the progress of the task. The propertyChange method is invoked each time progress changes.

See Worker Threads and SwingWorker in Concurrency in Swing for more data about SwingWorker.

The background chore in ProgressBarDemo simulates a real job by reporting random amounts of progress at random intervals. The propertyChange method responds to changes in the chore'south progress property past updating the progress bar:

public void propertyChange(PropertyChangeEvent evt) {     if (!done) {         int progress = task.getProgress();            progressBar.setValue(progress);            taskOutput.append(String.format(                 "Completed %d%% of job.\n", progress));     }          

When the background job is consummate, the task'southward done method resets the progress bar:

public void washed() {     //Tell progress listener to stop updating progress bar.     done = truthful;     Toolkit.getDefaultToolkit().beep();     startButton.setEnabled(truthful);     setCursor(naught); //turn off the await cursor            progressBar.setValue(progressBar.getMinimum());            taskOutput.append("Washed!\n"); }          

Notation that the washed method sets the done field to truthful, preventing propertyChange from making further updates to the progress bar. This is necessary because the final updates to the progress property may occur after washed is invoked.

Using Indeterminate Mode

In ProgressBarDemo2 indeterminate mode is set until actual progress begins:

public void propertyChange(PropertyChangeEvent evt) {     if (!washed) {         int progress = task.getProgress();         if (progress == 0) {            progressBar.setIndeterminate(true);            taskOutput.suspend("No progress yet\due north");         } else {            progressBar.setIndeterminate(false);                        progressBar.setString(null);             progressBar.setValue(progress);             taskOutput.append(String.format(                     "Completed %d%% of task.\northward", progress));         }     } }          

The other changes in the lawmaking are related to string display. A progress bar that displays a string is likely to be taller than ane that doesn't, and, every bit the demo designers, we've arbitrarily decided that this progress bar should display a string merely when it'southward in the default, determinate way. However, we want to avert the layout ugliness that might effect if the progress bar changed height when it changed modes. Thus, the code leaves in the call to setStringPainted(truthful) just adds a call to setString("") and so that no text will be displayed. Later, when the progress bar switches from indeterminate to determinate mode, invoking setString(null) makes the progress bar brandish its default string.

One change we did non make was removing the phone call to progressBar.setValue from the progress event handler. The call doesn't do any harm because an indeterminate progress bar doesn't utilise its value property, except possibly to display it in the status string. In fact, keeping the progress bar's data every bit up-to-engagement as possible is a practiced practice, since some look and feels might not support indeterminate mode.


Endeavour this:

  1. Click the Launch push button to run the ProgressBar2 Demo using Java™ Spider web Start (download JDK seven or afterwards). Alternatively, to compile and run the example yourself, consult the case alphabetize.Launches the ProgressBar2 Demo example
  2. Push the Start button. Notation that the progress bar starts animating as shortly as the button is pressed, and so switches back into determinate way (like ProgressBarDemo).

How to Use Progress Monitors

At present let'due south rewrite ProgressBarDemo to use a progress monitor instead of a progress bar. Here'due south a picture of the new demo program, ProgressMonitorDemo:

A snapshot of ProgressMonitorDemo and a dialog brought up by a progress monitor

Try this:

  1. Click the Launch push button to run the ProgressMonitor Demo using Coffee™ Web Starting time (download JDK vii or later). Alternatively, to compile and run the example yourself, consult the example index.Launches the ProgressMonitor Demo example
  2. Push the Commencement push button. After a certain amount of time, the program displays a progress dialog.
  3. Click the OK push button. Note that the chore continues even though the dialog is gone.
  4. Start some other task. Afterwards the dialog pops upwards, click the Cancel button. The dialog goes away and the task stops.

A progress monitor cannot be used again, so a new one must be created each fourth dimension a new job is started. This program creates a progress monitor each fourth dimension the user starts a new task with the Offset button.

Here'due south the statement that creates the progress monitor:

progressMonitor = new ProgressMonitor(ProgressMonitorDemo.this,                                       "Running a Long Task",                                       "", 0, task.getLengthOfTask());          

This lawmaking uses ProgressMonitor'south only constructor to create the monitor and initialize several arguments:

  • The starting time statement provides the parent component to the dialog popped upwards past the progress monitor.
  • The 2nd statement is a string that describes the nature of the chore being monitored. This cord is displayed on the dialog. encounter The Progress Monitoring API for details about this argument.
  • The third argument is some other cord that provides a changeable status annotation. The example uses an empty string to indicate that the dialog should make space for a changeable condition note, but that the note is initially empty. If you provide zilch for this statement, the notation is omitted from the dialog. The example updates the note each time the progress property changes. It updates the monitor's electric current value at the same time:
    int progress = chore.getProgress(); String message = String.format("Completed %d%%.\north", progress);                progressMonitor.setNote(bulletin); progressMonitor.setProgress(progress);                taskOutput.append(bulletin);              
  • The terminal two arguments provide the minimum and maximum values, respectively, for the progress bar displayed in the dialog.

Past default, a progress monitor waits a minimum of 500 milliseconds before deciding whether to pop upward the dialog. It also waits for the progress to become more than the minimum value. If it calculates that the task will take more than than 2000 milliseconds to consummate, the progress dialog appears. To adjust the minimum waiting period, invoke setMillisToDecidedToPopup. To adapt the minimum progress time required for a dialog to announced, invoke setMillisToPopup.

Past the simple fact that this case uses a progress monitor, information technology adds a feature that wasn't present in the version of the program that uses a progress bar: The user tin cancel the task past clicking the Cancel push on the dialog. Here's the code in the example that checks to meet if the user canceled the job or if the task exited normally:

if (progressMonitor.isCanceled() || chore.isDone()) {     progressMonitor.close();     Toolkit.getDefaultToolkit().beep();     if (progressMonitor.isCanceled()) {         task.cancel(true);         taskOutput.suspend("Task canceled.\n");     } else {         taskOutput.append("Task completed.\n");     }     startButton.setEnabled(true); }          

Annotation that the progress monitor doesn't itself cancel the job. It provides the GUI and API to allow the plan to do then hands.

Deciding Whether to Use a Progress Bar or a Progress Monitor

Utilize a progress bar if:

  • You want more control over the configuration of the progress bar. If y'all are working directly with a progress bar, y'all tin ready it to be indeterminate, make information technology display vertically, provide a string for information technology to brandish, annals change listeners on it, and provide information technology with a bounded range model to control the progress bar's minimum, maximum, and current values.
  • The program needs to display other components along with the progress bar.
  • You demand more than than one progress bar. With some tasks, you need to monitor more than i parameter. For instance, an installation programme might monitor disk space usage in addition to how many files have been successfully installed.
  • You need to reuse the progress bar. A progress bar tin be reused; a progress monitor cannot. In one case the progress monitor has decided to brandish a dialog (or not), the progress monitor cannot practice information technology over again.

Use a progress monitor if:

  • You want an like shooting fish in a barrel way to display progress in a dialog.
  • The running task is secondary and the user might not exist interested in the progress of the chore. Progress monitor provides a way for the user to dismiss the dialog while the task is even so running.
  • Y'all want an easy way for the chore to be cancelled. Progress monitor provides a GUI for the user to cancel the job. All yous have to exercise is call progress monitor's isCanceled method to find out if the user pressed the Abolish push.
  • Your task displays a short message periodically while running. The progress monitor dialog provides the setNote method and then that the task can provide further information about what it's doing. For example, an installation task might written report the proper noun of each file every bit it's installed.
  • The job might non take a long time to complete. You decide at what point a running task is taking long enough to warrant letting the user know about it. Progress monitor won't popular upwardly a dialog if the task completes within the timeframe you set.

If yous make up one's mind to apply a progress monitor and the task you lot are monitoring is reading from an input stream, use the ProgressMonitorInputStream form.

The Progress Monitoring API

The following tables listing the usually used API for using progress bars and progress monitors. Because JProgressBar is a subclass of JComponent, other methods you are likely to call on a JProgressBar are listed in The JComponent Form. Annotation that ProgressMonitor is a bracket of Object and is not a visual component.

The API for monitoring progress falls into these categories:

  • Creating the Progress Bar
  • Setting or Getting the Progress Bar's Constraints/Values
  • Controlling the Progress Bar'southward Advent
  • Creating the Progress Monitor
  • Configuring the Progress Monitor
  • Terminating the Progress Monitor
Creating the Progress Bar
Constructor Purpose
JProgressBar()
JProgressBar(int, int)
Create a horizontal progress bar. The no-statement constructor initializes the progress bar with a minimum and initial value of 0 and a maximum of 100. The constructor with two integer arguments specifies the minimum and maximum values.
JProgressBar(int)
JProgressBar(int, int, int)
Create a progress bar with the specified orientation, which can be either JProgressBar.HORIZONTAL or JProgressBar.VERTICAL. The optional second and third arguments specify minimum and maximum values.
JProgressBar(BoundedRangeModel) Create a horizontal progress bar with the specified range model.
Setting or Getting the Progress Bar'southward Constraints/Values
Method Purpose
void setValue(int)
int getValue()
Set or go the electric current value of the progress bar. The value is constrained by the minimum and maximum values.
double getPercentComplete() Get the percent consummate for the progress bar.
void setMinimum(int)
int getMinimum()
Set or go the minimum value of the progress bar.
void setMaximum(int)
int getMaximum()
Set or get the maximum value of the progress bar.
void setModel(BoundedRangeModel)
BoundedRangeModel getModel()
Set or become the model used past the progress bar. The model establishes the progress bar's constraints and values, so yous tin can use it directly as an alternative to using the individual gear up/get methods listed in a higher place.
Controlling the Progress Bar's Appearance
Method Purpose
void setIndeterminate(boolean) By specifying true, put the progress bar into indeterminate mode. Specifying false puts the progress bar back into its default, determinate mode.
void setOrientation(int)
int getOrientation()
Ready or get whether the progress bar is vertical or horizontal. Acceptable values are JProgressBar.VERTICAL or JProgressBar.HORIZONTAL.
void setBorderPainted(boolean)
boolean isBorderPainted()
Set up or get whether the progress bar has a border.
void setStringPainted(boolean)
boolean isStringPainted()
Set or get whether the progress bar displays a percent string. By default, the value of the percentage string is the value returned by getPercentComplete formatted as a pct. Yous tin set the string to exist displayed with setString.
void setString(String)
String getString()
Set or get the percent string.
Creating the Progress Monitor
Method or Constructor Purpose
ProgressMonitor(Component, Object, Cord, int, int) Create a progress monitor. The Component argument is the parent for the monitor'south dialog. The Object argument is a bulletin to put on the selection pane within the dialog. The value of this object is typically a Cord. The String argument is a changeable condition notation. The final 2 int arguments set the minimum and maximum values, respectively, for the progress bar used in the dialog.
ProgressMonitor getProgressMonitor()
(in ProgressMonitorInputStream)
Gets a progress monitor that monitors reading from an input stream.
Configuring the Progress Monitor
Method Purpose
void setMinimum(int)
int getMinimum()
Set or get the minimum value of the progress monitor. This value is used by the monitor to prepare the progress bar in the dialog.
void setMaximum(int)
int getMaximum()
Ready or get the maximum value of the progress monitor. This value is used by the monitor to prepare the progress bar in the dialog.
void setProgress(int) Update the monitor's progress.
void setNote(String)
String getNote()
Ready or become the status note. This note is displayed on the dialog. To omit the condition note from the dialog, provide null every bit the third statement to the monitor'south constructor.
void setMillisToDecideToPopup(int)
int getMillisToDecideToPopup()
Set or go the time after which the monitor should determine whether to popup a dialog.
Terminating the Progress Monitor
Method Purpose
void shut() Close the progress monitor. This disposes of the dialog.
boolean isCanceled() Determine whether the user pressed the Cancel push.

Examples that Monitor Progress

This following examples use JProgressBar or ProgressMonitor.

Case Where Described Notes
ProgressBarDemo This department Uses a basic progress bar to evidence progress on a task running in a divide thread.
ProgressBarDemo2 This section Uses a bones progress bar to prove progress on a task running in a separate thread.
ProgressMonitorDemo This section Modification of the previous example that uses a progress monitor instead of a progress bar.

If y'all are programming in JavaFX, encounter Progress Bar and Progress Indicator.

C++ Read Text From File Show Progress

Source: https://docs.oracle.com/javase/tutorial/uiswing/components/progress.html

0 Response to "C++ Read Text From File Show Progress"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel