The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
Sometimes a task 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 work, and perhaps the amount of progress, is to use an animated image.指示工作的一种方式,可能是进度的数量,是使用动画图像。
Another way of indicating work is to set the wait cursor, using the 指示工作的另一种方法是使用Cursor
class and the Component
-defined setCursor
method. Cursor
类和Component
定义的setCursor
方法设置等待游标。For example, the following code makes the wait cursor be displayed when the cursor is over 例如,以下代码使当光标位于container
(including any components it contains that have no cursor specified):container
上时显示等待光标(包括它包含的未指定光标的任何组件):
container.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
To convey how complete a task is, you can use a progress bar like this one:要传达任务的完成程度,可以使用如下进度条:
Sometimes you can't immediately determine the length of a long-running task, or the task might stay stuck at the same 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 mode displays animation to indicate that work is occurring. 不确定模式下的进度条显示动画以指示正在进行工作。As soon as the progress bar can display more meaningful information, you should switch it back into its default, determinate mode. 一旦进度条能够显示更多有意义的信息,您就应该将其切换回默认的确定模式。In the Java look and feel, indeterminate progress bars look like this:在Java外观中,不确定进度条如下所示:
Swing provides three classes to help you use progress bars:Swing提供了三个类来帮助您使用进度条:
JProgressBar
ProgressMonitor
ProgressMonitorInputStream
getProgressMonitor
and configure it as described in How to Use Progress Monitors.getProgressMonitor
来获取流的进度监视器,并按照如何使用进度监视器中的描述进行配置。After you see a progress bar and a progress monitor in action, Deciding Whether to Use a Progress Bar or a Progress Monitor can help you figure out which is appropriate for your application.在看到进度条和进度监视器运行后,决定使用进度条还是进度监视器可以帮助您找出适合您的应用程序的方法。
Here's a picture of a small demo application that uses a progress bar to measure the progress of a task that runs in its own thread:下面是一个小型演示应用程序的图片,它使用进度条来测量在自己线程中运行的任务的进度:
The following code, from 来自ProgressBarDemo.java
, creates and sets up the progress bar:ProgressBarDemo.java
的以下代码创建并设置进度条:
//Where member variables are declared: JProgressBar progressBar; ... //Where the GUI is constructed: progressBar = new JProgressBar(0, task.getLengthOfTask()); progressBar.setValue(0); progressBar.setStringPainted(true);
The constructor that creates the progress bar sets the progress bar's minimum and maximum values. 创建进度条的构造函数设置进度条的最小值和最大值。You can also set these values with 您还可以使用setMinimum
and setMaximum
. setMinimum
和setMaximum
设置这些值。The minimum and maximum values used in this program are 0 and the length of the task, which is typical of many programs and tasks. 该程序中使用的最小值和最大值为0和任务长度,这是许多程序和任务的典型值。However, a progress bar's minimum and maximum values can be any value, even negative. 但是,进度条的最小值和最大值可以是任何值,甚至是负值。The code snippet also sets the progress bar's current value to 0.代码段还将进度条的当前值设置为0。
The call to 调用setStringPainted
causes the progress bar to display, within its bounds, a textual indication of the percentage of the task that has completed. setStringPainted
会导致进度条在其边界内显示已完成任务百分比的文本指示。By default, the progress bar displays the value returned by its 默认情况下,进度条显示其getPercentComplete
method formatted as a percent, such as 33%. getPercentComplete
方法返回的值,格式为百分比,例如33%
。Alternatively, you can replace the default with a different string by calling 或者,您可以通过调用setString
. setString
将默认值替换为其他字符串。For example,例如
if (/*...half way done...*/) progressBar.setString("Half way there!");
When the user clicks Start, an instance of the inner class 当用户单击开始时,将创建并执行内部类任务的实例。Task
is created and executed.
public void actionPerformed(ActionEvent evt) { startButton.setEnabled(false); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); done = false; task = new Task(); task.addPropertyChangeListener(this); task.execute(); }
Task
is a subclass of 是javax.swing.SwingWorker
. javax.swing.SwingWorker
的子类。The Task
instance does three important things for ProgressBarDemo
:Task
实例为ProgressBarDemo
做了三件重要的事情:
doInBackground
in a separate thread. doInBackground
。done
method in the event-dispatching thread.done
方法。progress
, that is updated to indicate the progress of the task. progress
,该属性被更新以指示任务的进度。propertyChange
method is invoked each time progress
changes.progress
更改时都会调用propertyChange
方法。See Worker Threads and SwingWorker in Concurrency in Swing for more information about 有关SwingWorker
.SwingWorker
的更多信息,请参阅Swing中的并发中的工作线程和SwingWorker。
The background task in ProgressBarDemo
simulates a real task by reporting random amounts of progress at random intervals. ProgressBarDemo
中的后台任务通过以随机间隔报告随机进度来模拟真实任务。The propertyChange
method responds to changes in the task's progress
property by updating the progress bar:propertyChange
方法通过更新进度栏来响应任务progress
属性的更改:
public void propertyChange(PropertyChangeEvent evt) { if (!done) { int progress = task.getProgress(); progressBar.setValue(progress); taskOutput.append(String.format( "Completed %d%% of task.\n", progress)); }
When the background task is complete, the task's 后台任务完成后,任务的完成方法将重置进度条:done
method resets the progress bar:
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 progressBar.setValue(progressBar.getMinimum()); taskOutput.append("Done!\n"); }
Note that the 请注意,done
method sets the done
field to true
, preventing propertyChange
from making further updates to the progress bar. done
方法将done
字段设置为true
,从而防止propertyChange
对进度条进行进一步更新。This is necessary because the final updates to the 这是必要的,因为对progress
property may occur after done
is invoked.progress
属性的最终更新可能在调用done
之后发生。
In 在ProgressBarDemo2
indeterminate mode is set until actual progress begins:ProgressBarDemo2
中,设置不确定模式,直到实际进度开始:
public void propertyChange(PropertyChangeEvent evt) { if (!done) { int progress = task.getProgress(); if (progress == 0) { progressBar.setIndeterminate(true); taskOutput.append("No progress yet\n"); } else { progressBar.setIndeterminate(false); progressBar.setString(null); progressBar.setValue(progress); taskOutput.append(String.format( "Completed %d%% of task.\n", progress)); } } }
The other changes in the code are related to string display. 代码中的其他更改与字符串显示有关。A progress bar that displays a string is likely to be taller than one that doesn't, and, as the demo designers, we've arbitrarily decided that this progress bar should display a string only when it's in the default, determinate mode. 显示字符串的进度条可能比不显示的进度条高,而且,作为演示设计师,我们任意决定该进度条仅在默认的确定模式下显示字符串。However, we want to avoid the layout ugliness that might result if the progress bar changed height when it changed modes. 然而,我们希望避免当进度条改变模式时改变高度可能导致的布局丑陋。Thus, the code leaves in the call to 因此,代码保留了对setStringPainted(true)
but adds a call to setString("")
so that no text will be displayed. setStringPainted(true)
的调用,但添加了对setString("")
的调用,因此不会显示任何文本。Later, when the progress bar switches from indeterminate to determinate mode, invoking 稍后,当进度条从不确定模式切换到确定模式时,调用setString(null)
makes the progress bar display its default string.setString(null)
将使进度条显示其默认字符串。
One change we did not make was removing the call to 我们没有做的一个更改是从progressBar.setValue
from the progress
event handler. progress
事件处理程序中删除对progressBar.setValue
的调用。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 data as up-to-date as possible is a good practice, since some look and feels might not support indeterminate mode.事实上,保持进度条的数据尽可能最新是一个很好的做法,因为有些外观可能不支持不确定模式。
Now let's rewrite ProgressBarDemo to use a progress monitor instead of a progress bar. 现在,让我们重写ProgressBarDemo以使用进度监视器而不是进度条。Here's a picture of the new demo program, ProgressMonitorDemo:以下是新演示程序ProgressMonitorDemo的图片:
A progress monitor cannot be used again, so a new one must be created each time a new task is started. 无法再次使用进度监视器,因此每次启动新任务时都必须创建一个新的进度监视器。This program creates a progress monitor each time the user starts a new task with the Start button.每次用户使用“开始”按钮启动新任务时,该程序都会创建一个进度监视器。
Here's the statement that creates the progress monitor:下面是创建进度监视器的语句:
progressMonitor = new ProgressMonitor(ProgressMonitorDemo.this, "Running a Long Task", "", 0, task.getLengthOfTask());
This code uses 此代码使用ProgressMonitor
's only constructor to create the monitor and initialize several arguments:ProgressMonitor
的唯一构造函数创建监视器并初始化几个参数:
null
for this argument, the note is omitted from the dialog. null
,则该注释将从对话框中省略。progress
property changes. progress
属性更改时更新注释。int progress = task.getProgress(); String message = String.format("Completed %d%%.\n", progress); progressMonitor.setNote(message); progressMonitor.setProgress(progress); taskOutput.append(message);
By default, a progress monitor waits a minimum of 500 milliseconds before deciding whether to pop up the dialog. 默认情况下,进度监视器在决定是否弹出对话框之前至少等待500毫秒。It also waits for the progress to become more than the minimum value. 它还等待进度超过最小值。If it calculates that the task will take more than 2000 milliseconds to complete, the progress dialog appears. 如果计算出任务完成时间超过2000毫秒,则会显示“进度”对话框。To adjust the minimum waiting period, invoke 要调整最小等待时间,请调用setMillisToDecidedToPopup
. setMillistodedTopopup
。To adjust the minimum progress time required for a dialog to appear, invoke 要调整对话框显示所需的最小进度时间,请调用setMillisToPopup
.setMillistopup
。
By the simple fact that this example uses a progress monitor, it adds a feature that wasn't present in the version of the program that uses a progress bar: The user can cancel the task by clicking the Cancel button on the dialog. 由于本示例使用进度监视器这一简单事实,它添加了一个在使用进度条的程序版本中不存在的功能:用户可以通过单击对话框上的“取消”按钮取消任务。Here's the code in the example that checks to see if the user canceled the task or if the task exited normally:下面是示例中检查用户是否取消任务或任务是否正常退出的代码:
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); }
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.它提供了GUI和API,以允许程序轻松地执行此操作。
Use a progress bar if:在以下情况下使用进度条:
Use a progress monitor if:在以下情况下使用进度监视器:
isCanceled
method to find out if the user pressed the Cancel button.isCanceled
方法,以确定用户是否按下了取消按钮。setNote
method so that the task can provide further information about what it's doing. setNote
方法,以便任务可以提供有关其正在执行的操作的进一步信息。If you decide to use a progress monitor and the task you are monitoring is reading from an input stream, use the 如果您决定使用进度监视器,并且正在监视的任务正在从输入流读取,请使用ProgressMonitorInputStream
class.ProgressMonitorInputStream
类。
The following tables list the commonly used API for using progress bars and progress monitors. 下表列出了使用进度条和进度监视器的常用API。Because 因为JProgressBar
is a subclass of JComponent
, other methods you are likely to call on a JProgressBar
are listed in The JComponent Class. JProgressBar
是JComponent
的子类,所以您可能在JProgresBar
上调用的其他方法都列在JComponnt
类中。Note that 请注意,ProgressMonitor
is a subclass of Object
and is not a visual component.ProgressMonitor
是Object
的子类,不是可视化组件。
The API for monitoring progress falls into these categories:用于监控进度的API分为以下几类:
JProgressBar() JProgressBar(int, int) |
|
JProgressBar(int) JProgressBar(int, int, int) |
JProgressBar.HORIZONTAL or JProgressBar.VERTICAL . JProgressBar.HORIZONTAL 或JProgressBar.VERTICAL 。 |
JProgressBar(BoundedRangeModel) |
void setValue(int) int getValue() |
|
double getPercentComplete() |
|
void setMinimum(int) int getMinimum() |
|
void setMaximum(int) int getMaximum() |
|
void setModel(BoundedRangeModel) BoundedRangeModel getModel() |
void setIndeterminate(boolean) |
true , put the progress bar into indeterminate mode. true ,将进度条置于不确定模式。false puts the progress bar back into its default, determinate mode.false 会将进度条返回到默认的确定模式。 |
void setOrientation(int) int getOrientation() |
JProgressBar.VERTICAL or JProgressBar.HORIZONTAL .JProgressBar.VERTICAL 或JProgressBar.HORIZONTAL 。 |
void setBorderPainted(boolean) boolean isBorderPainted() |
|
void setStringPainted(boolean) boolean isStringPainted() |
getPercentComplete formatted as a percent. getPercentComplete 返回的值。setString .setString 设置要显示的字符串。 |
void setString(String) String getString() |
ProgressMonitor(Component, Object, String, int, int) |
Component argument is the parent for the monitor's dialog. Component 参数是监视器对话框的父项。Object argument is a message to put on the option pane within the dialog. Object 参数是要放在对话框的选项窗格上的消息。String . String 。String argument is a changeable status note. String 参数是一个可更改的状态注释。int arguments set the minimum and maximum values, respectively, for the progress bar used in the dialog.int 参数分别设置对话框中使用的进度条的最小值和最大值。 |
ProgressMonitor getProgressMonitor() (in ProgressMonitorInputStream ) |
void setMinimum(int) int getMinimum() |
|
void setMaximum(int) int getMaximum() |
|
void setProgress(int) |
|
void setNote(String) String getNote() |
null as the third argument to the monitor's constructor.null 作为监视器构造函数的第三个参数。 |
void setMillisToDecideToPopup(int) int getMillisToDecideToPopup() |
void close() |
|
boolean isCanceled() |
This following examples use 以下示例使用JProgressBar
or ProgressMonitor
.JProgressBar
或ProgressMonitor
。
ProgressBarDemo |
||
ProgressBarDemo2 |
||
ProgressMonitorDemo |
If you are programming in JavaFX, see Progress Bar and Progress Indicator.如果您使用JavaFX编程,请参阅进度条和进度指示器。