⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 progress.html

📁 jsf、swing的官方指南
💻 HTML
📖 第 1 页 / 共 3 页
字号:
    See <a href="#bars">Using Determinate Progress Bars</a>    for information and an example of using a typical progress bar.    The section <a href="#indeterminate">Using Indeterminate Mode</a>    tells you how to animate a progress bar to show activity    before the task's scope is known.<dt><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/ProgressMonitor.html"><strong><code>ProgressMonitor</code></strong></a><dd><em>Not</em> a visible component.    Instead, an instance of this class    monitors the progress of a task and    pops up a <a href="dialog.html">dialog</a> if necessary.    See <a href="#monitors">How to Use Progress Monitors</a>    for details and an example of using a progress monitor.<dt><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/ProgressMonitorInputStream.html"><strong><code>ProgressMonitorInputStream</code></strong></a><dd>An input stream with an attached progress monitor,    which monitors reading from the stream.    You use an instance of this stream like any of the other    input streams described in<a class="TutorialLink" target="_top" href="../../essential/io/index.html">Basic I/O</a>.    You can get the stream's progress monitor    with a call to <code>getProgressMonitor</code>    and configure it as described in    <a href="#monitors">How to Use Progress Monitors</a>.</dl>After you see a progress bar and a progress monitor in action,<a href="#deciding">Deciding Whether to Use a Progress Bar or a Progress Monitor</a>can help you figure out which is appropriate for your application.</blockquote><a name="bars"><h3>Using Determinate Progress Bars</h3></a><blockquote>Here's a picture of a small demo application thatuses a progress bar to measure the progress of a taskthat runs in its own thread:<p><center><IMG SRC="../../figures/uiswing/components/ProgressBarDemo.png" WIDTH="281" HEIGHT="203" ALIGN="BOTTOM" ALT="A snapshot of ProgressBarDemo, which uses a progress bar"></center></p><blockquote><hr><strong>Try this:</strong>&nbsp;<ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/ProgressBarDemo.jnlp">Run ProgressBarDemo</a> (it requires release 6) using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java<sup><font size=-2>TM</font></sup> Web Start</a>.    Or, to compile and run the example yourself,     consult the     <a href="examples/index.html#ProgressBarDemo">example index</a>.<p><li> Push the <strong>Start</strong> button.     The demo puts up a wait cursor     and starts updating      the progress bar.     The task displays its output in the text area     at the bottom of the window.</ol><hr></blockquote>Below is the code from<a class="SourceLink" target="_blank" href="examples/ProgressBarDemo.java"><code>ProgressBarDemo.java</code></a>that creates and sets up the progress bar:<blockquote><pre><em>//Where member variables are declared:</em>JProgressBar progressBar;...<em>//Where the GUI is constructed:</em>progressBar = new JProgressBar(0, task.getLengthOfTask());progressBar.setValue(0);progressBar.setStringPainted(true);</pre></blockquote>The constructor that creates the progress barsets the progress bar's minimum and maximum values.You can also set these values with <code>setMinimum</code>and <code>setMaximum</code>.The minimum and maximum values used in this program are 0 and thelength of the task, which is typical of many programs and tasks.However, a progress bar's minimum and maximumvalues can be any value, even negative.The code snippet also sets the progress bar's current value to 0.<p>The call to <code>setStringPainted</code>causes the progress bar to display, within its bounds,a textual indication of the percentage of the task that has completed.By default, the progress bar displays the valuereturned by its <code>getPercentComplete</code> methodformatted as a percent, such as <strong>33%</strong>.Alternatively, you can replace the default with a differentstring by calling <code>setString</code>. For example,<blockquote><pre>if (<em>/*...half way done...*/</em>)    progressBar.setString("Half way there!");</pre></blockquote><p>When the user clicks <b>Start</b>, an instance of the inner class<code>Task</code> is created and executed. <blockquote><pre>public void actionPerformed(ActionEvent evt) {    startButton.setEnabled(false);    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));    done = false;    <b>task = new Task();    task.addPropertyChangeListener(this);    task.execute();</b>}</pre></blockquote><code>Task</code> is asubclass of<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html"><code>javax.swing.SwingWorker</code></a>. The <code>Task</code> instance does three important things for<code>ProgressBarDemo</code>:<ol>    <li>The instance invokes the <code>doInBackground</code> in a    separate 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.    <li>When the background task is complete, the instance invokes the    <code>done</code> method in the event-dispatching thread.    <li>The instance maintains a bound property,    <code>progress</code>, that is updated to indicate the progress of    the task. The <code>propertyChange</code> method is invoked each    time <code>progress</code> changes.</ol>See <a class="TutorialLink" target="_top" href="../concurrency/worker.html">Worker Threads and SwingWorker</a>in<a class="TutorialLink" target="_top" href="../concurrency/index.html">Concurrency in Swing</a>for more information about <code>SwingWorker</code>.<p>The background task in <code>ProgressBarDemo</code> simulates a realtask by reporting random amounts of progress at random intervals. The<code>propertyChange</code> method responds to changes in the thetask's <code>progress</code> property by updating the progress bar:<blockquote><pre>public void propertyChange(PropertyChangeEvent evt) {    if (!done) {        int progress = task.getProgress();        <b>progressBar.setValue(progress);</b>        taskOutput.append(String.format(                "Completed %d%% of task.\n", progress));    }</pre></blockquote><p>When the background task is complete, the task's <code>done</code>method resets the progress bar:<blockquote><pre>public void done() {    //Tell progress listener to stop updating progress bar.    done = true;    Toolkit.getDefaultToolkit().beep();    startButton.setEnabled(true);    setCursor(null); //turn off the wait cursor    <b>progressBar.setValue(progressBar.getMinimum());</b>    taskOutput.append("Done!\n");}</pre></blockquote>Note that the <code>done</code> method sets the <code>done</code>field to <code>true</code>, preventing <code>propertyChange</code>from making further updates to the progress bar. This is necessarybecause the final updates to the <code>progress</code> property mayocccur after <code>done</code> is invoked.</blockquote><a name="indeterminate"><h3>Using Indeterminate Mode</h3></a><blockquote>In <code>ProgressBarDemo2</code> indeterminate mode is set untilactual progress begins:<blockquote><pre>public void propertyChange(PropertyChangeEvent evt) {    if (!done) {        int progress = task.getProgress();        if (progress == 0) {            <b>progressBar.setIndeterminate(true);</b>            taskOutput.append("No progress yet\n");        } else {            <b>progressBar.setIndeterminate(false); </b>            progressBar.setString(null);            progressBar.setValue(progress);            taskOutput.append(String.format(                    "Completed %d%% of task.\n", progress));        }    }}</pre></blockquote><p>The other changes in the code are related to string display.A progress bar that displays a string is likely to be tallerthan one that doesn't,and, as the demo designers, we've arbitarily decided that this progress barshould display a string only when it's in the default, determinate mode.However, we want to avoid the layout uglinessthat might result if the progress bar changed heightwhen it changed modes.Thus, the code leaves in the call to<code>setStringPainted(true)</code>but adds a call to <code>setString("")</code>so that no text will be displayed.Later, when the progress bar switches from indeterminate to determinate mode,invoking <code>setString(null)</code> makes the progress bar display its default string.<p>One change we did <em>not</em> makewas removing the call to <code>progressBar.setValue</code>from the <code>progress</code> event handler.The call doesn't do any harm because an indeterminate progress bar doesn't use its value property,except perhaps to display it in the status string.In fact, keeping the progress bar's dataas up-to-date as possible is a good practice,since some look and feels might not support indeterminate mode.</p><blockquote><hr><strong>Try this:</strong>&nbsp;<ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/ProgressBarDemo2.jnlp">Run ProgressBarDemo2</a> (it requires release 6) using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>.    Or, to compile and run the example yourself,     consult the     <a href="examples/index.html#ProgressBarDemo2">example index</a>.<p><li> Push the <strong>Start</strong> button.     Note that the progress bar starts animating as soon as     the button is pressed,     and then switches back into     determinate mode (like ProgressBarDemo).</ol><hr></blockquote></blockquote><a name="monitors"><h3>How to Use Progress Monitors</h3></a><blockquote>Now let's rewrite ProgressBarDemo to use a progressmonitor instead of a progress bar.Here's a picture of the new demo program,ProgressMonitorDemo:<p><center><IMG SRC="../../figures/uiswing/components/ProgressMonitorDemo.png" WIDTH="469" HEIGHT="267" ALIGN="BOTTOM" ALT="A snapshot of ProgressMonitorDemo and a dialog brought up by a progress monitor"></center></p><blockquote><hr><strong>Try this:</strong>&nbsp;<ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/ProgressMonitorDemo.jnlp">Run ProgressMonitorDemo</a> (it requires release 6) using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>.    Or, to compile and run the example yourself,     consult the     <a href="examples/index.html#ProgressMonitorDemo">example index</a>. <li> Push the <strong>Start</strong> button.     After a certain amount of time, the program displays a progress dialog.<li> Click the <strong>OK</strong> button.     Note that the task continues even though the dialog is gone.<li> Start another task. After the dialog pops up,     click the <strong>Cancel</strong> button.     The dialog goes away and the task stops.</ol><hr></blockquote>A progress monitor cannot be used again, so a newone must be created each time a new task is started.This program creates a progress monitor each time theuser starts a new task with the <strong>Start</strong> button.<p>Here's the statement that creates the progress monitor:<blockquote><pre>progressMonitor = new ProgressMonitor(ProgressMonitorDemo.this,                                      "Running a Long Task",                                      "", 0, task.getLengthOfTask());</pre></blockquote>This code uses <code>ProgressMonitor</code>'s only constructorto create the monitor andinitialize several arguments:<ul><li> The first argument provides the parent component to     the dialog popped up by the progress monitor.<li> The second argument is a string that describes     the nature of the task being monitored.     This string is displayed on the dialog.     see <a href="#api">The Progress Monitoring API</a>     for details about this argument.<li> The third argument is another string     that provides a changeable status note.     The example uses an empty string to indicate that     the dialog should make space for a changeable status note,     but that the note is initially empty.     If you provide <code>null</code> for this argument,     the note is omitted from the dialog.     The example updates the note      each time the <code>progress</code> property changes.     It updates the monitor's current value at the same time:<blockquote><pre>int progress = task.getProgress();String message = String.format("Completed %d%%.\n", progress);<b>progressMonitor.setNote(message);progressMonitor.setProgress(progress);</b>taskOutput.append(message);</pre></blockquote><li> The last two arguments provide the minimum and maximum     values, respectively, for the progress bar displayed in the dialog.</ul>By default, a progress monitor waits a minium of 500 millisecondsbefore deciding whether to pop up the dialog. It also waits for theprogress to become more than the minimum value. If it calculates thatthe task will take more than 2000 milliseconds to complete, theprogress dialog appears. To adjust the minimum waiting period, invoke<code>setMillisToDecidedToPopup</code>. To adjust the minimum progresstime required for a dialog to appear, invoke<code>setMillisToPopup</code>.<p>By the simple fact that this example uses a progress monitor,it adds a feature that wasn't present in the version of theprogram that uses a progress bar:The user can cancel the task by clicking the <strong>Cancel</strong>button on the dialog.Here's the code in the example that checksto see if the user canceled the task or if the task exited normally:<blockquote><pre>if (progressMonitor.isCanceled() || task.isDone()) {    progressMonitor.close();    Toolkit.getDefaultToolkit().beep();    if (progressMonitor.isCanceled()) {        task.cancel(true);        taskOutput.append("Task canceled.\n");    } else {        taskOutput.append("Task completed.\n");    }    startButton.setEnabled(true);}</pre></blockquote>Note that the progress monitor doesn't itself cancel the task.It provides the GUI and API to allow the program to do so easily.</blockquote><a name="deciding"><h3>Deciding Whether to Use a Progress Bar or a Progress Monitor</h3></a><blockquote>Use a <em>progress bar</em> if:<ul><li> You want more control over the configuration of the progress bar.     If you are working directly with a progress bar,     you can     set it to be indeterminate,     make it display vertically,     provide a string for it to display,     register change listeners on it, and     provide it with a bounded range model to control     the progress bar's minimum, maximum, and current values.<li> The program needs to display other components     along with the progress bar.<li> You need more than one progress bar.     With some tasks, you need to monitor more than one parameter.     For example, an installation program might monitor     disk space usage in addition to how many files     have been successfully installed.    <li> You need to reuse the progress bar.     A progress bar can be reused; a progress monitor cannot.     Once the progress monitor has decided to display a dialog (or not),     the progress monitor cannot do it again.</ul><p>Use a <em>progress monitor</em> if:<ul><li> You want an easy way to display progress     in a <a href="dialog.html">dialog</a>.<li> The running task is secondary and     the user might not be interested in the progress of the task.     Progress monitor provides a way for the user to     dismiss the dialog while the task is still running.<li> You want an easy way for the task to be cancelled.     Progress monitor provides a GUI for the user to cancel the task.     All you have to do is     call progress monitor's <code>isCanceled</code> method to find out     if the user pressed the <strong>Cancel</strong> button.<li> Your task displays a short message periodically while running.     The progress monitor dialog provides the <code>setNote</code>     method so that the task can provide further information about what     it's doing. For example, an installation task might report the     name of each file as it's installed.<li> The task might not 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 pop up a dialog if the task completes     within the timeframe you set.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -