List of usage examples for javax.swing JProgressBar setValue
@BeanProperty(bound = false, preferred = true, description = "The progress bar's current value.") public void setValue(int n)
From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java
private static HeliosData loadHelios() throws IOException { System.out.println("Finding Helios implementation"); HeliosData data = new HeliosData(); boolean needsToDownload = !IMPL_FILE.exists(); if (!needsToDownload) { try (JarFile jarFile = new JarFile(IMPL_FILE)) { ZipEntry entry = jarFile.getEntry("META-INF/MANIFEST.MF"); if (entry == null) { needsToDownload = true;//ww w. ja v a2s . co m } else { Manifest manifest = new Manifest(jarFile.getInputStream(entry)); String ver = manifest.getMainAttributes().getValue("Implementation-Version"); try { data.buildNumber = Integer.parseInt(ver); data.version = manifest.getMainAttributes().getValue("Version"); data.mainClass = manifest.getMainAttributes().getValue("Main-Class"); } catch (NumberFormatException e) { needsToDownload = true; } } } catch (IOException e) { needsToDownload = true; } } if (needsToDownload) { URL latestJar = new URL(LATEST_JAR); System.out.println("Downloading latest Helios implementation"); FileOutputStream out = new FileOutputStream(IMPL_FILE); HttpURLConnection connection = (HttpURLConnection) latestJar.openConnection(); if (connection.getResponseCode() == 200) { int contentLength = connection.getContentLength(); if (contentLength > 0) { InputStream stream = connection.getInputStream(); byte[] buffer = new byte[1024]; int amnt; AtomicInteger total = new AtomicInteger(); AtomicBoolean stop = new AtomicBoolean(false); Thread progressBar = new Thread() { public void run() { JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); JLabel label = new JLabel(); label.setText("Downloading latest Helios build"); panel.add(label); GridLayout layout = new GridLayout(); layout.setColumns(1); layout.setRows(3); panel.setLayout(layout); JProgressBar pbar = new JProgressBar(); pbar.setMinimum(0); pbar.setMaximum(100); panel.add(pbar); JTextArea textArea = new JTextArea(1, 3); textArea.setOpaque(false); textArea.setEditable(false); textArea.setText("Downloaded 00.00MB/00.00MB"); panel.add(textArea); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setContentPane(panel); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); while (!stop.get()) { SwingUtilities.invokeLater( () -> pbar.setValue((int) (100.0 * total.get() / contentLength))); textArea.setText("Downloaded " + bytesToMeg(total.get()) + "MB/" + bytesToMeg(contentLength) + "MB"); try { Thread.sleep(100); } catch (InterruptedException ignored) { } } frame.dispose(); } }; progressBar.start(); while ((amnt = stream.read(buffer)) != -1) { out.write(buffer, 0, amnt); total.addAndGet(amnt); } stop.set(true); return loadHelios(); } else { throw new IOException("Content-Length set to " + connection.getContentLength()); } } else if (connection.getResponseCode() == 404) { // Most likely bootstrapper is out of date throw new RuntimeException("Bootstrapper out of date!"); } else { throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage()); } } return data; }
From source file:com.roche.iceboar.progressview.ProgressUpdater.java
public ProgressUpdater(JProgressBar progressBar, JLabel messageLabel, ProgressEventFactory progressEventFactory) { this.progressBar = progressBar; this.messageLabel = messageLabel; this.events = new HashSet<ProgressEvent>(progressEventFactory.getAllProgressEvents()); amountOfEvents = events.size();//ww w. j av a 2 s .c om progressBar.setMinimum(0); progressBar.setMaximum(amountOfEvents); progressBar.setValue(0); progressBar.setString("0 %"); }
From source file:com.moss.appprocs.swing.ProgressMonitorBean.java
private void update() { if (log.isDebugEnabled()) log.debug("Updating " + process.name()); ProgressReport report = process.progressReport(); super.getLabelTaskname().setText(process.name()); super.getLabelDescription().setText(process.description()); final JProgressBar pBar = getProgressBar(); String string = report.accept(new ProgressReportVisitor<String>() { public String visit(BasicProgressReport r) { getCommandButton().setEnabled(false); pBar.setIndeterminate(true); return r.describe() + "..."; }//from w ww . ja v a 2 s . c om public String visit(TrackableProgressReport t) { pBar.setIndeterminate(false); pBar.setMinimum(0); pBar.setMaximum((int) t.length()); pBar.setValue((int) t.progress()); return t.describe(); } }); if (process.state() == State.STOPPABLE) { stopButton().setEnabled(true); } else { stopButton().setEnabled(false); } pBar.setString(string); }
From source file:com.enderville.enderinstaller.util.InstallScript.java
/** * Installs the specified list of mods, updating the gui as it goes. * * @param mods The list of mods to install. * @param text The text area to update with logging statements. * @param progressBar The progress bar to update. *///from w w w .ja v a 2 s.c o m public static void guiInstall(List<String> mods, JTextArea text, JProgressBar progressBar) { //Create backups to restore if the install fails. try { createBackup(); } catch (IOException e) { text.append("Failed to create backup copies of minecraft.jar and mods folder"); LOGGER.error("Failed to create backup copies of minecraft.jar and mods folder", e); return; } //Create a temp directory where we can unpack the jar and install mods. File tmp; try { tmp = getTempDir(); } catch (IOException e) { text.append("Error creating temp directory!"); LOGGER.error("Install Error", e); return; } if (!tmp.mkdirs()) { text.append("Error creating temp directory!"); return; } File mcDir = new File(InstallerConfig.getMinecraftFolder()); File mcJar = new File(InstallerConfig.getMinecraftJar()); File reqDir = new File(InstallerConfig.getRequiredModsFolder()); //Calculate the number of "tasks" for the progress bar. int reqMods = 0; for (File f : reqDir.listFiles()) { if (f.isDirectory()) { reqMods++; } } //3 "other" steps: unpack, repack, delete temp int baseTasks = 3; int taskSize = reqMods + mods.size() + baseTasks; progressBar.setMinimum(0); progressBar.setMaximum(taskSize); int task = 1; try { text.append("Unpacking minecraft.jar\n"); unpackMCJar(tmp, mcJar); progressBar.setValue(task++); text.append("Installing Core mods\n"); //TODO specific ordering required! for (File mod : reqDir.listFiles()) { if (!mod.isDirectory()) { continue; } String name = mod.getName(); text.append("...Installing " + name + "\n"); installMod(mod, tmp, mcDir); progressBar.setValue(task++); } if (!mods.isEmpty()) { text.append("Installing Extra mods\n"); //TODO specific ordering required! for (String name : mods) { File mod = new File(FilenameUtils .normalize(FilenameUtils.concat(InstallerConfig.getExtraModsFolder(), name))); text.append("...Installing " + name + "\n"); installMod(mod, tmp, mcDir); progressBar.setValue(task++); } } text.append("Repacking minecraft.jar\n"); repackMCJar(tmp, mcJar); progressBar.setValue(task++); } catch (Exception e) { text.append("!!!Error installing mods!!!"); LOGGER.error("Installation error", e); try { restoreBackup(); } catch (IOException ioe) { text.append("Error while restoring backup files minecraft.jar.backup and mods_backup folder\n!"); LOGGER.error("Error while restoring backup files minecraft.jar.backup and mods_backup folder!", ioe); } } text.append("Deleting temporary files\n"); try { FileUtils.deleteDirectory(tmp); progressBar.setValue(task++); } catch (IOException e) { text.append("Error deleting temporary files!\n"); LOGGER.error("Install Error", e); return; } text.append("Finished!"); }
From source file:org.duracloud.syncui.SyncUIDriver.java
/** * Note: The embedded Jetty server setup below is based on the example configuration in the Eclipse documentation: * https://www.eclipse.org/jetty/documentation/9.4.x/embedded-examples.html#embedded-webapp-jsp *//*www . j a va2s.co m*/ private static void launchServer(final String url, final CloseableHttpClient client) { try { final JDialog dialog = new JDialog(); dialog.setSize(new java.awt.Dimension(400, 75)); dialog.setModalityType(ModalityType.MODELESS); dialog.setTitle("DuraCloud Sync"); dialog.setLocationRelativeTo(null); JPanel panel = new JPanel(); final JLabel label = new JLabel("Loading..."); final JProgressBar progress = new JProgressBar(); progress.setStringPainted(true); panel.add(label); panel.add(progress); dialog.add(panel); dialog.setVisible(true); port = SyncUIConfig.getPort(); contextPath = SyncUIConfig.getContextPath(); Server srv = new Server(port); // Setup JMX MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); srv.addBean(mbContainer); ProtectionDomain protectionDomain = org.duracloud.syncui.SyncUIDriver.class.getProtectionDomain(); String warFile = protectionDomain.getCodeSource().getLocation().toExternalForm(); log.debug("warfile: {}", warFile); WebAppContext context = new WebAppContext(); context.setContextPath(contextPath); context.setWar(warFile); context.setExtractWAR(Boolean.TRUE); Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(srv); classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration", "org.eclipse.jetty.annotations.AnnotationConfiguration"); context.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$"); srv.setHandler(context); new Thread(new Runnable() { @Override public void run() { createSysTray(url, srv); while (true) { if (progress.getValue() < 100) { progress.setValue(progress.getValue() + 3); } sleep(2000); if (isAppRunning(url, client)) { break; } } progress.setValue(100); label.setText("Launching browser..."); launchBrowser(url); dialog.setVisible(false); } }).start(); srv.start(); srv.join(); } catch (Exception e) { log.error("Error launching server: " + e.getMessage(), e); } }
From source file:io.gameover.utilities.pixeleditor.Pixelizer.java
public JProgressBar getToleranceBar() { if (toleranceBar == null) { toleranceBar = new JProgressBar(); toleranceBar.setPreferredSize(new Dimension(200, 25)); toleranceBar.setValue(10);/*from w ww . j a v a2s . c om*/ toleranceBar.setMaximum(100); toleranceBar.setStringPainted(true); toleranceBar.addMouseListener(new MouseAdapter() { public boolean mouseEntered = false; @Override public void mouseReleased(MouseEvent e) { if (mouseEntered) { JProgressBar pb = (JProgressBar) e.getComponent(); pb.setValue((int) ((((double) e.getX()) / pb.getSize().getWidth()) * 100d)); pb.updateUI(); } } @Override public void mouseEntered(MouseEvent e) { this.mouseEntered = true; } @Override public void mouseExited(MouseEvent e) { this.mouseEntered = false; } }); } return toleranceBar; }
From source file:marytts.tools.voiceimport.DatabaseImportMain.java
/** * Run the selected components in a different thread. * *//*w w w . j a va 2 s . c om*/ protected void runSelectedComponents() { new Thread("RunSelectedComponentsThread") { public void run() { try { runButton.setEnabled(false); for (int i = 0; i < components.length; i++) { if (checkboxes[i].isSelected()) { boolean success = false; Container parent = checkboxes[i].getParent(); final JProgressBar progress = new JProgressBar(); final VoiceImportComponent oneComponent = components[i]; if (oneComponent.getProgress() != -1) { progress.setStringPainted(true); new Thread("ProgressThread") { public void run() { int percent = 0; while (progress.isVisible()) { progress.setValue(percent); try { Thread.sleep(500); } catch (InterruptedException ie) { } percent = oneComponent.getProgress(); } } }.start(); } else { progress.setIndeterminate(true); } parent.add(progress, BorderLayout.EAST); progress.setVisible(true); parent.validate(); try { success = oneComponent.compute(); } catch (Exception exc) { checkboxes[i].setBackground(Color.RED); throw new Exception("The component " + checkboxes[i].getText() + " produced the following exception: ", exc); } finally { checkboxes[i].setSelected(false); progress.setVisible(false); } if (success) { checkboxes[i].setBackground(Color.GREEN); } else { checkboxes[i].setBackground(Color.RED); } } } } catch (Throwable e) { e.printStackTrace(); } finally { runButton.setEnabled(true); } } }.start(); }
From source file:bemap.TrackOrganiser.java
/** * Data treatment that has to be done after the import can be added here: * For instance://w w w .j av a 2 s . c om * Splits the imported tracks into several tracks after the import. */ public void postImportTreatment(JProgressBar progressBar) throws JSONException { BeMapEditor.mainWindow.append("\nTreatment..."); int indexOfImportedTrack = currentTrack.getID(); if (TRACK_DEBUG) BeMapEditor.mainWindow.append("\nImport track:" + indexOfImportedTrack); Data importTrack = currentTrack; int firstTrackID = currentTrack.getFirstTrackID(); int lastTrackID = currentTrack.getLastTrackID(); if (TRACK_DEBUG) BeMapEditor.mainWindow.append("\nFirst track: " + firstTrackID + " Last track: " + lastTrackID); progressBar.setMinimum(firstTrackID); progressBar.setMaximum(lastTrackID); for (int i = firstTrackID; i <= lastTrackID; i++) { progressBar.setValue(i); int nb = importTrack.getNumberOfPoints(i); if (nb >= MIN_NB_POINTS_IMPORT) { createNewTrack("Track " + i + "-" + BeMapEditor.mainWindow.getUsrIDofConnectedDevice()); if (TRACK_DEBUG) BeMapEditor.mainWindow.append("\nTrack " + i + " has " + nb + " points."); currentTrack.importJSONList(importTrack.exportJSONLayer(i)); } else if (TRACK_DEBUG) BeMapEditor.mainWindow.append("\nTrack " + i + " has " + nb + " points: No track created!"); } //delete import track deleteTrack(indexOfImportedTrack); BeMapEditor.mainWindow.append("\nTreatment ok!"); }
From source file:jcan2.SimpleSerial.java
public int importDataFromDevice(JProgressBar progressBar, JTextArea status) throws InterruptedException, JSONException { if ("Error - no Port found".equals(serialPortName)) return -1; else {//from w w w. j a v a 2 s . c o m SerialPort serialPort = new SerialPort(serialPortName); try { serialPort.openPort();//Open serial port serialPort.setParams(SerialPort.BAUDRATE_115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0); serialPort.writeBytes("$ORUSR*11\n".getBytes());//Write data to port Thread.sleep(WAIT_MS); String userString = serialPort.readString(); int usr = decodeUserID(userString); if (usr > 0) { BeMapEditor.mainWindow.setUsr(usr); status.append("\nUser ID: " + usr); } else if (usr == -1) { //code for getting usr id from server //$ORUSR,25*11\n status.append("\nError: Getting user ID from server not yet supported!"); BeMapEditor.mainWindow.setUsr(-1); } else { status.append("\nError: No User ID found! Import aborted."); return -1; } serialPort.writeBytes("$ORNUM*11\n".getBytes()); Thread.sleep(WAIT_MS); String numberString = serialPort.readString(); int totalNumber = decodeNbPoints(numberString); if (totalNumber > 0) status.append("\nNumber of points to import: " + totalNumber); else if (totalNumber == 0) { status.append("\nNo points stored to import! "); return 0; } else { status.append("\nError: Number of Points"); return -1; } //prepare track to import BeMapEditor.trackOrganiser.createNewTrack("Import"); int nbRequests = (totalNumber / (MAX_DATA_PER_IMPORT)) + 1; int rest = totalNumber - (nbRequests - 1) * MAX_DATA_PER_IMPORT; //nb of points for the last request if (SERIAL_DEBUG) BeMapEditor.mainWindow.append("\nNumber of requests necessary: " + nbRequests); if (SERIAL_DEBUG) BeMapEditor.mainWindow.append("\nPoints resting for last request: " + rest); //init progress bar progressBar.setMaximum(nbRequests); for (int i = 0; i < (nbRequests - 1); i++) { //import serie of points int offset = i * MAX_DATA_PER_IMPORT; if (importSerieOfPoints(serialPort, MAX_DATA_PER_IMPORT, offset) < 0) return 0; //actualize progress bar progressBar.setValue(i + 1); } int final_offset = (nbRequests - 1) * MAX_DATA_PER_IMPORT; if (importSerieOfPoints(serialPort, rest, final_offset) < 0) return 0; //import the rest of the points progressBar.setValue(nbRequests); status.append("\n" + totalNumber + " Points successfully imported"); serialPort.writeString("$ORMEM*11\n"); Thread.sleep(WAIT_MS); decodeMemoryState(serialPort.readString()); serialPort.closePort();//Close serial port BeMapEditor.trackOrganiser.postImportTreatment(progressBar); return 1; } catch (SerialPortException ex) { return 0;//do not print error } } }
From source file:bemap.SimpleSerial.java
public int importDataFromDevice(JProgressBar progressBar, JTextArea status) throws InterruptedException, JSONException { if ("Error - no Port found".equals(serialPortName)) return -1; else {/*ww w . j a v a 2 s .c om*/ SerialPort serialPort = new SerialPort(serialPortName); try { serialPort.openPort();//Open serial port serialPort.setParams(SerialPort.BAUDRATE_115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0); serialPort.writeBytes("$ORUSR*11\n".getBytes());//Write data to port Thread.sleep(WAIT_MS); String userString = serialPort.readString(); int usr = decodeUserID(userString); if (usr > 0) { BeMapEditor.mainWindow.setUsr(usr); status.append("\nUser ID: " + usr); } else if (usr == -1) { //code for getting usr id from server //$ORUSR,25*11\n status.append("\nError: No user ID set!"); BeMapEditor.mainWindow.setUsr(-1); } else { status.append("\nError: No User ID found! Import aborted."); return -1; } //import settings serialPort.writeBytes("$ORCFG*11\n".getBytes());//Write data to port Thread.sleep(WAIT_MS); String configString = serialPort.readString(); if (decodeSettings(configString) == 1 && SERIAL_DEBUG) { BeMapEditor.mainWindow.append("\nSettings decoded"); } else BeMapEditor.mainWindow.append("\nError decoding settings"); //Start importing points serialPort.writeBytes("$ORNUM*11\n".getBytes()); Thread.sleep(WAIT_MS); String numberString = serialPort.readString(); int totalNumber = decodeNbPoints(numberString); if (totalNumber > 0) status.append("\nNumber of points to import: " + totalNumber); else if (totalNumber == 0) { status.append("\nNo points stored to import! "); return 0; } else { status.append("\nError: Number of Points"); return -1; } //prepare track to import BeMapEditor.trackOrganiser.createNewTrack("Import"); int nbRequests = (totalNumber / (MAX_DATA_PER_IMPORT)) + 1; int rest = totalNumber - (nbRequests - 1) * MAX_DATA_PER_IMPORT; //nb of points for the last request if (SERIAL_DEBUG) BeMapEditor.mainWindow.append("\nNumber of requests necessary: " + nbRequests); if (SERIAL_DEBUG) BeMapEditor.mainWindow.append("\nPoints resting for last request: " + rest); //init progress bar progressBar.setMaximum(nbRequests); for (int i = 0; i < (nbRequests - 1); i++) { //import serie of points int offset = i * MAX_DATA_PER_IMPORT; if (importSerieOfPoints(serialPort, MAX_DATA_PER_IMPORT, offset) < 0) return 0; //actualize progress bar progressBar.setValue(i + 1); } int final_offset = (nbRequests - 1) * MAX_DATA_PER_IMPORT; if (importSerieOfPoints(serialPort, rest, final_offset) < 0) return 0; //import the rest of the points progressBar.setValue(nbRequests); status.append("\n" + totalNumber + " Points successfully imported"); serialPort.writeString("$ORMEM*11\n"); Thread.sleep(WAIT_MS); decodeMemoryState(serialPort.readString()); serialPort.closePort();//Close serial port BeMapEditor.trackOrganiser.postImportTreatment(progressBar); return 1; } catch (SerialPortException ex) { return 0;//do not print error } } }