下面列出了怎么用javax.swing.ProgressMonitor的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Add all the frames from an AnimationReader.
*
* @param r
* the animation to read.
* @param monitor
* an optional ProgressMonitor to update
* @throws IOException
* if an error occurs copying frames.
*/
public void addFrames(AnimationReader r, ProgressMonitor monitor)
throws IOException {
if (monitor != null)
monitor.setMaximum(r.getFrameCount());
BufferedImage bi = r.getNextFrame(false);
int ctr = 1;
while (bi != null) {
if (monitor != null) {
if (monitor.isCanceled()) {
throw new UserCancelledException();
}
monitor.setProgress(ctr);
}
float d;
try {
d = (float) r.getFrameDuration();
} catch (Exception e) {
e.printStackTrace();
d = 1;
}
addFrame(d, bi, .98f);
bi = r.getNextFrame(false);
ctr++;
}
}
public RanksResult(JFrame parent,Ranks ranks,int bestNRanks,boolean ascendant){
super(parent,true);
//this.parent=parent;
this.bestNRanks=bestNRanks;
this.ranks=ranks;
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.factorCompare=ascendant?-1:1;
this.maxJump=ranks.getMaxJump();
this.stackWidth=ranks.getStackWidth();
progressMonitor=new ProgressMonitor(parent,AIRanksTool.getUIText("Result_Progress_Message"),"",0,100);
progressMonitor.setProgress(0);
task = new Task();
task.addPropertyChangeListener(this);
task.execute();
}
@Override
public void actionPerformed(ActionEvent event) {
String path = pathField.getText();
if (path.trim().isEmpty()) {
JOptionPane.showMessageDialog(this, "A file path must be selected.", "Empty File Path", JOptionPane.ERROR_MESSAGE);
return;
}
File selectedFile = new File(path);
if (selectedFile.exists()) {
this.setVisible(false);
int option = JOptionPane.showConfirmDialog(cliGuiCtx.getMainWindow(), "Overwrite " + path, "Overwrite?", JOptionPane.YES_NO_OPTION);
if (option == JOptionPane.NO_OPTION) {
this.setVisible(true);
return;
}
}
this.dispose();
progressMonitor = new ProgressMonitor(cliGuiCtx.getMainWindow(), "Downloading " + fileName, "", 0, 100);
progressMonitor.setProgress(0);
downloadTask = new DownloadLogTask(selectedFile);
downloadTask.addPropertyChangeListener(this);
downloadTask.execute();
}
public void run(JComponent parent, final Runnable calc, String title) {
bFinished = false;
progressMonitor = new ProgressMonitor(parent,
title, "", 0, 100);
progressMonitor.setProgress(0);
progressMonitor.setMillisToDecideToPopup(0);
timer = new Timer(100, new TimerListener());
final SwingWorker worker = new SwingWorker() {
public Object construct() {
thread = new Thread(calc);
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
return null;
}
};
worker.start();
timer.start();
}
public ProgressMonitorWrapper(String msg, Runnable task) {
pbar = new ProgressMonitor(null, msg, "Elapsed: 0 secs", 0, 4);
start_time = System.currentTimeMillis();
timer = new Timer(500, this);
timer.start();
thread = new Thread(() -> {
task.run();
timer.stop();
pbar.close();
});
thread.start();
}
public static void main(String[] args) throws Exception {
createTestUI();
monitor = new ProgressMonitor(frame, "Progress", null, 0, 100);
robotThread = new TestThread();
robotThread.start();
for (counter = 0; counter <= 100; counter += 10) {
Thread.sleep(1000);
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
if (!monitor.isCanceled()) {
monitor.setProgress(counter);
System.out.println("Progress bar is in progress");
}
}
});
if (monitor.isCanceled()) {
break;
}
}
disposeTestUI();
if (counter >= monitor.getMaximum()) {
throw new RuntimeException("Escape key did not cancel the ProgressMonitor");
}
}
MyGrabber(ProgressMonitor monitor, Image image, int x, int y, int width, int height, int[] values, int start,
int scan) {
super(image, x, y, width, height, values, start, scan);
this.monitor = monitor;
progress = 0;
goal = width * height;
monitor.setMinimum(0);
monitor.setMaximum(goal * 21 / 20);
}
ExportThread(Frame frame, Canvas canvas, File dest, ImageFileFilter f, List<Circuit> circuits, double scale,
boolean printerView, ProgressMonitor monitor) {
this.frame = frame;
this.canvas = canvas;
this.dest = dest;
this.filter = f;
this.circuits = circuits;
this.scale = scale;
this.printerView = printerView;
this.monitor = monitor;
}
@Override
public InputStream getProgressMonitorInputStream(InputStream in, int length, String msg) {
ProgressMonitorInputStream pmin = new ProgressMonitorInputStream(parent, msg, in);
ProgressMonitor pm = pmin.getProgressMonitor();
if (length > 0) {
pm.setMaximum(length);
}
return pmin;
}
/**
* Builder
* @param parent Parent frame
* @param ds Data set node
* @param pm Progress monitor
*/
PartitionCreator(Experiments parent, DataSet ds, ProgressMonitor pm) {
super();
this.ds = ds;
this.missingPartitions = ds.getMissingVector();
this.parent = parent;
this.pm = pm;
}
private void handleDownloadStarted()
{
logDebug("handleDownloadStarted: launching progress monitor");
GUIUtils.processOnSwingEventThread(new Runnable()
{
public void run()
{
final JFrame frame = controller.getMainFrame();
progressMonitor =
new ProgressMonitor(frame, i18n.DOWNLOADING_UPDATES_MSG, i18n.DOWNLOADING_UPDATES_MSG, 0,
totalFiles);
setProgress(0);
}
});
}
/**
* Saves the current images to the given destination using the current format
* writer.
*/
public void save(final Location id) {
if (images == null) return;
wait(true);
try {
myWriter.setDest(id);
final boolean stack = myWriter.canDoStacks();
final ProgressMonitor progress = new ProgressMonitor(this, "Saving " + id,
null, 0, stack ? images.length : 1);
if (stack) {
// save entire stack
for (int i = 0; i < images.length; i++) {
progress.setProgress(i);
final boolean canceled = progress.isCanceled();
myWriter.savePlane(0, i, getPlane(images[i]));
if (canceled) break;
}
progress.setProgress(images.length);
}
else {
// save current image only
myWriter.savePlane(0, 0, getPlane(getImage()));
progress.setProgress(1);
}
myWriter.close();
}
catch (FormatException | IOException exc) {
logService.info("", exc);
}
wait(false);
}
private void saveAll(boolean export) {
JadxArgs decompilerArgs = wrapper.getArgs();
if ((!decompilerArgs.isFsCaseSensitive() && !decompilerArgs.isRenameCaseSensitive())
|| !decompilerArgs.isRenameValid() || !decompilerArgs.isRenamePrintable()) {
JOptionPane.showMessageDialog(
this,
NLS.str("msg.rename_disabled", settings.getLangLocale()),
NLS.str("msg.rename_disabled_title", settings.getLangLocale()),
JOptionPane.INFORMATION_MESSAGE);
}
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setToolTipText(NLS.str("file.save_all_msg"));
Path currentDirectory = settings.getLastSaveFilePath();
if (currentDirectory != null) {
fileChooser.setCurrentDirectory(currentDirectory.toFile());
}
int ret = fileChooser.showSaveDialog(mainPanel);
if (ret == JFileChooser.APPROVE_OPTION) {
decompilerArgs.setExportAsGradleProject(export);
if (export) {
decompilerArgs.setSkipSources(false);
decompilerArgs.setSkipResources(false);
} else {
decompilerArgs.setSkipSources(settings.isSkipSources());
decompilerArgs.setSkipResources(settings.isSkipResources());
}
settings.setLastSaveFilePath(fileChooser.getCurrentDirectory().toPath());
ProgressMonitor progressMonitor = new ProgressMonitor(mainPanel, NLS.str("msg.saving_sources"), "", 0, 100);
progressMonitor.setMillisToPopup(0);
wrapper.saveAll(fileChooser.getSelectedFile(), progressMonitor);
}
}
public ExportProcessMonitorDialog(AbstractProcess<Void, DataExportStatus> exportProcess, JFrame parentFrame, RecordsToExport recordsToExport, DataFormat exportFormat, EarthSurveyService earthSurveyService, File exportToFile, LocalPropertiesService localPropertiesService ) {
super();
this.process = exportProcess;
this.recordsToExport = recordsToExport;
this.exportFormat = exportFormat;
this.earthSurveyService = earthSurveyService;
this.exportToFile = exportToFile;
this.localPropertiesService = localPropertiesService;
progressMonitor = new ProgressMonitor(parentFrame, Messages.getString("ExportDialogProcessMonitor.0"), Messages.getString("ExportDialogProcessMonitor.1"), 0, 100); //$NON-NLS-1$ //$NON-NLS-2$
progressMonitor.setMillisToPopup(1000);
}
public ImportProcessMonitorDialog(AbstractProcess<Void, ReferenceDataImportStatus<ParsingError>> importProcess, JFrame parentFrame ) {
super();
this.process = importProcess;
this.parentFrame = parentFrame;
SwingUtilities.invokeLater( () -> {
progressMonitor = new ProgressMonitor(parentFrame, Messages.getString("ExportDialogProcessMonitor.0"), Messages.getString("ExportDialogProcessMonitor.1"), 0, 100); //$NON-NLS-1$ //$NON-NLS-2$
progressMonitor.setMillisToPopup(1000);
} );
}
/**
*
* @Title: testPerformed
* @Description: Test Menu Item Performed
* @param @param item
* @return void
* @throws
*/
private void testPerformed(JMenuItem item)
{
if (RESTConst.START_TEST.equals(item.getText()))
{
if (MapUtils.isEmpty(RESTCache.getHists()))
{
return;
}
miStart.setEnabled(false);
miStop.setEnabled(true);
HttpHists hists = new HttpHists(RESTCache.getHists().values());
pm = new ProgressMonitor(RESTView.getView(), RESTConst.TEST_CASE, "", 0, hists.getTotal());
pm.setProgress(0);
task = new HistTask(hists);
task.addPropertyChangeListener(this);
task.execute();
testThrd = new TestThd(hists);
testThrd.setName(RESTConst.TEST_THREAD);
RESTThdPool.getInstance().getPool().submit(testThrd);
}
if (RESTConst.STOP_TEST.equals(item.getText()))
{
if (null == testThrd)
{
return;
}
try
{
miStop.setEnabled(false);
pm.close();
task.cancel(true);
testThrd.getHists().setStop(true);
testThrd.interrupt();
miStart.setEnabled(true);
}
catch(Exception ex)
{
log.error("Failed to interrupt test thread.", ex);
}
}
if (RESTConst.TEST_REPORT.equals(item.getText()))
{
TestUtil.open(RESTConst.REPORT_HTML,
RESTConst.MSG_REPORT,
RESTConst.TEST_REPORT);
}
}
private void updateFontList() {
Runnable whenDone = new Runnable() {
@Override
public void run() {
fontListUpdated();
}
};
this.continuation = whenDone;
setModal(true);
final GetFontsWorker worker = new GetFontsWorker(this, showFixed, size, style);
progressMonitor = new ProgressMonitor(this,
Catalog.get("MSG_TakingInventory"),// NOI18N
" ", // NOI18N
0, 2);
// TMP progressMonitor.setMillisToDecideToPopup(0);
// TMP progressMonitor.setMillisToPopup(0);
// kick-start it so the progress dialog becomes visible.
progressMonitor.setProgress(1);
// Track notifications from worker and update pogressMonitor
worker.addPropertyChangeListener(new PropertyChangeListener() {
private boolean ckCancel() {
// SwingWorker queues up "progress" notificatons so
// it's possible that we receive some after SwingWorker.done()
// is called! If we then call setProgress() it "resurrects"
// a closed ProgresMonitor.
if (worker.isCancelled()) {
return true;
} else if (progressMonitor == null || progressMonitor.isCanceled()) {
boolean withInterrupts = true;
worker.cancel(withInterrupts);
return true;
} else {
return false;
}
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
switch (evt.getPropertyName()) {
case "progress":// NOI18N
if (ckCancel())
return;
progressMonitor.setProgress((Integer) evt.getNewValue());
break;
case GetFontsWorker.PROP_NFONTS:
if (ckCancel())
return;
progressMonitor.setNote(Catalog.get("MSG_CheckingFixedWidth")); // NOI18N
progressMonitor.setMaximum((Integer) evt.getNewValue());
break;
}
}
});
worker.execute();
}
public static void toFile(Image img, File file, ProgressMonitor monitor) throws IOException, AWTException {
FileOutputStream out = new FileOutputStream(file);
new GifEncoder(img, monitor).write(out);
out.close();
}
public static void toFile(Image img, String filename, ProgressMonitor monitor) throws IOException, AWTException {
FileOutputStream out = new FileOutputStream(filename);
new GifEncoder(img, monitor).write(out);
out.close();
}
static void doExport(Project proj) {
// First display circuit/parameter selection dialog
Frame frame = proj.getFrame();
CircuitJList list = new CircuitJList(proj, true);
if (list.getModel().getSize() == 0) {
JOptionPane.showMessageDialog(proj.getFrame(), Strings.get("exportEmptyCircuitsMessage"),
Strings.get("exportEmptyCircuitsTitle"), JOptionPane.YES_NO_OPTION);
return;
}
OptionsPanel options = new OptionsPanel(list);
int action = JOptionPane.showConfirmDialog(frame, options, Strings.get("exportImageSelect"),
JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (action != JOptionPane.OK_OPTION)
return;
List<Circuit> circuits = list.getSelectedCircuits();
double scale = options.getScale();
boolean printerView = options.getPrinterView();
if (circuits.isEmpty())
return;
ImageFileFilter filter;
int fmt = options.getImageFormat();
switch (options.getImageFormat()) {
case FORMAT_GIF:
filter = new ImageFileFilter(fmt, Strings.getter("exportGifFilter"), new String[] { "gif" });
break;
case FORMAT_PNG:
filter = new ImageFileFilter(fmt, Strings.getter("exportPngFilter"), new String[] { "png" });
break;
case FORMAT_JPG:
filter = new ImageFileFilter(fmt, Strings.getter("exportJpgFilter"),
new String[] { "jpg", "jpeg", "jpe", "jfi", "jfif", "jfi" });
break;
default:
System.err.println("unexpected format; aborted"); // OK
return;
}
// Then display file chooser
Loader loader = proj.getLogisimFile().getLoader();
JFileChooser chooser = loader.createChooser();
if (circuits.size() > 1) {
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setDialogTitle(Strings.get("exportImageDirectorySelect"));
} else {
chooser.setFileFilter(filter);
chooser.setDialogTitle(Strings.get("exportImageFileSelect"));
}
int returnVal = chooser.showDialog(frame, Strings.get("exportImageButton"));
if (returnVal != JFileChooser.APPROVE_OPTION)
return;
// Determine whether destination is valid
File dest = chooser.getSelectedFile();
chooser.setCurrentDirectory(dest.isDirectory() ? dest : dest.getParentFile());
if (dest.exists()) {
if (!dest.isDirectory()) {
int confirm = JOptionPane.showConfirmDialog(proj.getFrame(), Strings.get("confirmOverwriteMessage"),
Strings.get("confirmOverwriteTitle"), JOptionPane.YES_NO_OPTION);
if (confirm != JOptionPane.YES_OPTION)
return;
}
} else {
if (circuits.size() > 1) {
boolean created = dest.mkdir();
if (!created) {
JOptionPane.showMessageDialog(proj.getFrame(), Strings.get("exportNewDirectoryErrorMessage"),
Strings.get("exportNewDirectoryErrorTitle"), JOptionPane.YES_NO_OPTION);
return;
}
}
}
// Create the progress monitor
ProgressMonitor monitor = new ProgressMonitor(frame, Strings.get("exportImageProgress"), null, 0, 10000);
monitor.setMillisToDecideToPopup(100);
monitor.setMillisToPopup(200);
monitor.setProgress(0);
// And start a thread to actually perform the operation
// (This is run in a thread so that Swing will update the
// monitor.)
new ExportThread(frame, frame.getCanvas(), dest, filter, circuits, scale, printerView, monitor).start();
}
private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed
signup.setEnabled(false);
loginButton.setEnabled(false);
user.setEnabled(false);
password.setEnabled(false);
final ProgressMonitor mon = new ProgressMonitor(this, "Logging In", "Connecting To Server", 0, 100);
mon.setMillisToDecideToPopup(0);
mon.setProgress(1);
new Thread() {
public void run() {
try {
mon.setProgress(40);
URL u = new URL("https://codename-one.appspot.com/getData?m=login&u=" + URLEncoder.encode(user.getText(), "UTF-8") +
"&p=" + URLEncoder.encode(password.getText(), "UTF-8"));
InputStream i = u.openStream();
byte[] b = new byte[4];
i.read(b);
i.close();
mon.setProgress(90);
// success
if(b[0] == 'O') {
Preferences p = Preferences.userNodeForPackage(getClass());
if(remember.isSelected()) {
p.put("user", user.getText());
p.put("pass", password.getText());
} else {
p.remove("user");
p.remove("pass");
}
globalPassword = password.getText();
globalUser = user.getText();
dispose();
} else {
signup.setEnabled(true);
loginButton.setEnabled(true);
user.setEnabled(true);
password.setEnabled(true);
// fail
if(b[0] == 'F') {
signup.setText("Login Failed, check user/password");
} else {
// unknown error maybe proxy
JOptionPane.showMessageDialog(LoginDialog.this, "Login Failed", "Unable to connect, check proxy settings", JOptionPane.ERROR_MESSAGE);
}
}
mon.close();
} catch (Exception ex) {
ex.printStackTrace();
signup.setEnabled(true);
loginButton.setEnabled(true);
user.setEnabled(true);
password.setEnabled(true);
JOptionPane.showMessageDialog(LoginDialog.this, "Login Failed", "Internal Error:\n" + ex, JOptionPane.ERROR_MESSAGE);
}
}
}.start();
}
private void run(Component attach) {
pm = new ProgressMonitor(attach, "", "Working...", 0, 100);
pm.setProgress(0);
t.addPropertyChangeListener(this);
t.execute();
}
/**
* Create the monitor dialog.
*
* @param parent the parent component.
* @param title the title of the monitor dialog.
* @param workLoad the maximum work to do.
*/
public HMProgressMonitorDialog( Component parent, String title, int workLoad ) {
this.parent = parent;
progressMonitor = new ProgressMonitor(parent, title, "", 0, workLoad);
progressMonitor.setProgress(0);
}