List of usage examples for javax.swing JOptionPane OK_OPTION
int OK_OPTION
To view the source code for javax.swing JOptionPane OK_OPTION.
Click Source Link
From source file:edu.harvard.mcz.imagecapture.encoder.UnitTrayLabelBrowser.java
public void makePDF() { boolean ok = false; String message = ""; try {//from w ww . j a v a2s .c om ok = LabelEncoder.printList(tableModel.getList()); } catch (PrintFailedException e1) { message = "PDF generation failed: " + e1.getMessage(); } if (ok) { message = "File labels.pdf was generated."; ((AbstractTableModel) jTable.getModel()).fireTableDataChanged(); } JOptionPane.showMessageDialog(thisFrame, message, "PDF Generation", JOptionPane.OK_OPTION); }
From source file:gate.corpora.CSVImporter.java
@Override protected List<Action> buildActions(final NameBearerHandle handle) { List<Action> actions = new ArrayList<Action>(); if (!(handle.getTarget() instanceof Corpus)) return actions; actions.add(new AbstractAction("Populate from CSV File") { @Override//from w ww . j av a2s . co m public void actionPerformed(ActionEvent e) { // display the populater dialog and return if it is cancelled if (JOptionPane.showConfirmDialog(null, dialog, "Populate From CSV File", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) != JOptionPane.OK_OPTION) return; // we want to run the population in a separate thread so we don't lock // up the GUI Thread thread = new Thread(Thread.currentThread().getThreadGroup(), "CSV Corpus Populater") { public void run() { try { // unescape the strings that define the format of the file and // get the actual chars char separator = StringEscapeUtils.unescapeJava(txtSeparator.getText()).charAt(0); char quote = StringEscapeUtils.unescapeJava(txtQuoteChar.getText()).charAt(0); // see if we can convert the URL to a File instance File file = null; try { file = Files.fileFromURL(new URL(txtURL.getText())); } catch (IllegalArgumentException iae) { // this will happen if someone enters an actual URL, but we // handle that later so we can just ignore the exception for // now and keep going } if (file != null && file.isDirectory()) { // if we have a File instance and that points at a directory // then.... // get all the CSV files in the directory structure File[] files = Files.listFilesRecursively(file, CSV_FILE_FILTER); for (File f : files) { // for each file... // skip directories as we don't want to handle those if (f.isDirectory()) continue; if (cboDocuments.isSelected()) { // if we are creating lots of documents from a single // file // then call the populate method passing through all the // options from the GUI populate((Corpus) handle.getTarget(), f.toURI().toURL(), txtEncoding.getText(), (Integer) textColModel.getValue(), cboFeatures.isSelected(), separator, quote); } else { // if we are creating a single document from a single // file // then call the createDoc method passing through all // the // options from the GUI createDoc((Corpus) handle.getTarget(), f.toURI().toURL(), txtEncoding.getText(), (Integer) textColModel.getValue(), cboFeatures.isSelected(), separator, quote); } } } else { // we have a single URL to process so... if (cboDocuments.isSelected()) { // if we are creating lots of documents from a single file // then call the populate method passing through all the // options from the GUI populate((Corpus) handle.getTarget(), new URL(txtURL.getText()), txtEncoding.getText(), (Integer) textColModel.getValue(), cboFeatures.isSelected(), separator, quote); } else { // if we are creating a single document from a single file // then call the createDoc method passing through all the // options from the GUI createDoc((Corpus) handle.getTarget(), new URL(txtURL.getText()), txtEncoding.getText(), (Integer) textColModel.getValue(), cboFeatures.isSelected(), separator, quote); } } } catch (Exception e) { // TODO give a sensible error message e.printStackTrace(); } } }; // let's leave the GUI nice and responsive thread.setPriority(Thread.MIN_PRIORITY); // lets get to it and do some actual work! thread.start(); } }); return actions; }
From source file:imageviewer.system.ImageViewerClient.java
private void initialize(CommandLine args) { // First, process all the different command line arguments that we // need to override and/or send onwards for initialization. boolean fullScreen = (args.hasOption("fullscreen")) ? true : false; String dir = (args.hasOption("dir")) ? args.getOptionValue("dir") : null; String type = (args.hasOption("type")) ? args.getOptionValue("type") : "DICOM"; String prefix = (args.hasOption("client")) ? args.getOptionValue("client") : null; LOG.info("Java home environment: " + System.getProperty("java.home")); // Logging system taken care of through properties file. Check // for JAI. Set up JAI accordingly with the size of the cache // tile and to recycle cached tiles as needed. verifyJAI();//from w w w . jav a 2s . co m TileCache tc = JAI.getDefaultInstance().getTileCache(); tc.setMemoryCapacity(32 * 1024 * 1024); TileScheduler ts = JAI.createTileScheduler(); ts.setPriority(Thread.MAX_PRIORITY); JAI.getDefaultInstance().setTileScheduler(ts); JAI.getDefaultInstance().setRenderingHint(JAI.KEY_CACHED_TILE_RECYCLING_ENABLED, Boolean.TRUE); // Set up the frame and everything else. First, try and set the // UI manager to use our look and feel because it's groovy and // lets us control the GUI components much better. try { UIManager.setLookAndFeel(new ImageViewerLookAndFeel()); LookAndFeelAddons.setAddon(ImageViewerLookAndFeelAddons.class); } catch (Exception exc) { LOG.error("Could not set imageViewer L&F."); } // Load up the ApplicationContext information... ApplicationContext ac = ApplicationContext.getContext(); if (ac == null) { LOG.error("Could not load configuration, exiting."); System.exit(1); } // Override the client node information based on command line // arguments...Make sure that the files are there, otherwise just // default to a local configuration. String hostname = new String("localhost"); try { hostname = InetAddress.getLocalHost().getHostName(); } catch (Exception exc) { } String[] gatewayConfigs = (prefix != null) ? (new String[] { "resources/server/" + prefix + "GatewayConfig.xml", (String) ac.getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG), "resources/server/" + hostname + "GatewayConfig.xml", "resources/server/localGatewayConfig.xml" }) : (new String[] { (String) ac.getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG), "resources/server/" + hostname + "GatewayConfig.xml", "resources/server/localGatewayConfig.xml" }); String[] nodeConfigs = (prefix != null) ? (new String[] { "resources/server/" + prefix + "NodeConfig.xml", (String) ac.getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE), "resources/server/" + hostname + "NodeConfig.xml", "resources/server/localNodeConfig.xml" }) : (new String[] { (String) ac.getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE), "resources/server/" + hostname + "NodeConfig.xml", "resources/server/localNodeConfig.xml" }); for (int loop = 0; loop < gatewayConfigs.length; loop++) { String s = gatewayConfigs[loop]; if ((s != null) && (s.length() != 0) && (!"null".equals(s))) { File f = new File(s); if (f.exists()) { ac.setProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG, s); break; } } } LOG.info("Using gateway config: " + ac.getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG)); for (int loop = 0; loop < nodeConfigs.length; loop++) { String s = nodeConfigs[loop]; if ((s != null) && (s.length() != 0) && (!"null".equals(s))) { File f = new File(s); if (f.exists()) { ac.setProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE, s); break; } } } LOG.info("Using client config: " + ac.getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE)); // Load the layouts and set the default window/level manager... LayoutFactory.initialize(); DefaultWindowLevelManager dwlm = new DefaultWindowLevelManager(); // Create the main JFrame, set its behavior, and let the // ApplicationPanel know the glassPane and layeredPane. Set the // menubar based on reading in the configuration menus. mainFrame = new JFrame("imageviewer"); try { ArrayList<Image> iconList = new ArrayList<Image>(); iconList.add(ImageIO.read(new File("resources/icons/mii.png"))); iconList.add(ImageIO.read(new File("resources/icons/mii32.png"))); mainFrame.setIconImages(iconList); } catch (Exception exc) { } mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { int confirm = ApplicationPanel.getInstance().showDialog( "Are you sure you want to quit imageViewer?", null, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, UIManager.getIcon("Dialog.shutdownIcon")); if (confirm == JOptionPane.OK_OPTION) { boolean hasUnsaved = SaveStack.getInstance().hasUnsavedItems(); if (hasUnsaved) { int saveResult = ApplicationPanel.getInstance().showDialog( "There is still unsaved data. Do you want to save this data in the local archive?", null, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION); if (saveResult == JOptionPane.CANCEL_OPTION) return; if (saveResult == JOptionPane.YES_OPTION) SaveStack.getInstance().saveAll(); } LOG.info("Shutting down imageServer local archive..."); try { ImageViewerClientNode.getInstance().shutdown(); } catch (Exception exc) { LOG.error("Problem shutting down imageServer local archive..."); } finally { System.exit(0); } } } }); String menuFile = (String) ApplicationContext.getContext().getProperty(ac.CONFIG_MENUS); String ribbonFile = (String) ApplicationContext.getContext().getProperty(ac.CONFIG_RIBBON); if (menuFile != null) { JMenuBar mb = new JMenuBar(); mb.setBackground(Color.black); MenuReader.parseFile(menuFile, mb); mainFrame.setJMenuBar(mb); ApplicationContext.getContext().setApplicationMenuBar(mb); } else if (ribbonFile != null) { RibbonReader rr = new RibbonReader(); JRibbon jr = rr.parseFile(ribbonFile); mainFrame.getContentPane().add(jr, BorderLayout.NORTH); ApplicationContext.getContext().setApplicationRibbon(jr); } mainFrame.getContentPane().add(ApplicationPanel.getInstance(), BorderLayout.CENTER); ApplicationPanel.getInstance().setGlassPane((JPanel) (mainFrame.getGlassPane())); ApplicationPanel.getInstance().setLayeredPane(mainFrame.getLayeredPane()); // Load specified plugins...has to occur after the menus are // created, btw. PluginLoader.initialize("config/plugins.xml"); // Detect operating system... String osName = System.getProperty("os.name"); ApplicationContext.getContext().setProperty(ApplicationContext.OS_NAME, osName); LOG.info("Detected operating system: " + osName); // Try and hack the searched library paths if it's windows so we // can add a local dll path... try { if (osName.contains("Windows")) { Field f = ClassLoader.class.getDeclaredField("usr_paths"); f.setAccessible(true); String[] paths = (String[]) f.get(null); String[] tmp = new String[paths.length + 1]; System.arraycopy(paths, 0, tmp, 0, paths.length); File currentPath = new File("."); tmp[paths.length] = currentPath.getCanonicalPath() + "/lib/dll/"; f.set(null, tmp); f.setAccessible(false); } } catch (Exception exc) { LOG.error("Error attempting to dynamically set library paths."); } // Get screen resolution... GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice() .getDefaultConfiguration(); Rectangle r = gc.getBounds(); LOG.info("Detected screen resolution: " + (int) r.getWidth() + "x" + (int) r.getHeight()); // Try and see if Java3D is installed, and if so, what version... try { VirtualUniverse vu = new VirtualUniverse(); Map m = vu.getProperties(); String s = (String) m.get("j3d.version"); LOG.info("Detected Java3D version: " + s); } catch (Throwable t) { LOG.info("Unable to detect Java3D installation"); } // Try and see if native JOGL is installed... try { System.loadLibrary("jogl"); ac.setProperty(ApplicationContext.JOGL_DETECTED, Boolean.TRUE); LOG.info("Detected native libraries for JOGL"); } catch (Throwable t) { LOG.info("Unable to detect native JOGL installation"); ac.setProperty(ApplicationContext.JOGL_DETECTED, Boolean.FALSE); } // Start the local client node to connect to the network and the // local archive running on this machine...Thread the connection // process so it doesn't block the imageViewerClient creating this // instance. We may not be connected to the given gateway, so the // socketServer may go blah... final boolean useNetwork = (args.hasOption("nonet")) ? false : true; ApplicationPanel.getInstance().addStatusMessage("ImageViewer is starting up, please wait..."); if (useNetwork) LOG.info("Starting imageServer client to join network - please wait..."); Thread t = new Thread(new Runnable() { public void run() { try { ImageViewerClientNode.getInstance( (String) ApplicationContext.getContext() .getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG), (String) ApplicationContext.getContext() .getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE), useNetwork); ApplicationPanel.getInstance().addStatusMessage("Ready"); } catch (Exception exc) { exc.printStackTrace(); } } }); t.setPriority(9); t.start(); this.fullScreen = fullScreen; mainFrame.setUndecorated(fullScreen); // Set the view to encompass the default screen. if (fullScreen) { Insets i = Toolkit.getDefaultToolkit().getScreenInsets(gc); mainFrame.setLocation(r.x + i.left, r.y + i.top); mainFrame.setSize(r.width - i.left - i.right, r.height - i.top - i.bottom); } else { mainFrame.setSize(1100, 800); mainFrame.setLocation(r.x + 200, r.y + 100); } if (dir != null) ApplicationPanel.getInstance().load(dir, type); timer = new Timer(); timer.schedule(new GarbageCollectionTimer(), 5000, 2500); mainFrame.setVisible(true); }
From source file:com._17od.upm.gui.DatabaseActions.java
public void changeMasterPassword() throws IOException, ProblemReadingDatabaseFile, CryptoException, PasswordDatabaseException, TransportException { if (getLatestVersionOfDatabase()) { //The first task is to get the current master password boolean passwordCorrect = false; boolean okClicked = true; do {/* ww w .j a va 2s .c o m*/ char[] password = askUserForPassword(Translator.translate("enterDatabasePassword")); if (password == null) { okClicked = false; } else { try { dbPers.load(database.getDatabaseFile(), password); passwordCorrect = true; } catch (InvalidPasswordException e) { JOptionPane.showMessageDialog(mainWindow, Translator.translate("incorrectPassword")); } } } while (!passwordCorrect && okClicked); //If the master password was entered correctly then the next step is to get the new master password if (passwordCorrect == true) { final JPasswordField masterPassword = new JPasswordField(""); boolean passwordsMatch = false; Object buttonClicked; //Ask the user for the new master password //This loop will continue until the two passwords entered match or until the user hits the cancel button do { JPasswordField confirmedMasterPassword = new JPasswordField(""); JOptionPane pane = new JOptionPane( new Object[] { Translator.translate("enterNewMasterPassword"), masterPassword, Translator.translate("confirmation"), confirmedMasterPassword }, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION); JDialog dialog = pane.createDialog(mainWindow, Translator.translate("changeMasterPassword")); dialog.addWindowFocusListener(new WindowAdapter() { public void windowGainedFocus(WindowEvent e) { masterPassword.requestFocusInWindow(); } }); dialog.show(); buttonClicked = pane.getValue(); if (buttonClicked.equals(new Integer(JOptionPane.OK_OPTION))) { if (!Arrays.equals(masterPassword.getPassword(), confirmedMasterPassword.getPassword())) { JOptionPane.showMessageDialog(mainWindow, Translator.translate("passwordsDontMatch")); } else { passwordsMatch = true; } } } while (buttonClicked.equals(new Integer(JOptionPane.OK_OPTION)) && !passwordsMatch); //If the user clicked OK and the passwords match then change the database password if (buttonClicked.equals(new Integer(JOptionPane.OK_OPTION)) && passwordsMatch) { this.dbPers.getEncryptionService().initCipher(masterPassword.getPassword()); saveDatabase(); } } } }
From source file:electroStaticUI.UserInput.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private void getChargeData() { numberOfCharges = Integer.parseInt(getNumberOfCharges.getText()); DefaultValues.allocatePointChargeArray(numberOfCharges); chargesToCalc = new PointCharge[numberOfCharges]; mapper = new CustomMapper(DefaultValues.getCircOrRect()); chargeDataFrame = new JFrame(); chargeDataFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JPanel chargeDataPanel = new JPanel(); chargeDataFrame.setTitle("Data For Charge #: " + (1 + okButtonPushes)); JLabel chargeLabel = new JLabel("Charge"); JLabel chargeUnitLabel = new JLabel("C"); charge = new JTextField(10); charge.setEditable(true);/*from w ww . j ava2s . co m*/ chargeModComboBox = new JComboBox(chargeModList); chargeModComboBox.setSelectedIndex(5); chargeModComboBox.setVisible(true); JLabel xPositionLabel = new JLabel("X Value"); xPosition = new JTextField(10); xPosition.setEditable(true); JLabel yPositionLabel = new JLabel("Y Value"); yPosition = new JTextField(10); yPosition.setEditable(true); //JLabel zPositionLabel = new JLabel("Z Value"); //JTextField zPosition = new JTextField(5); //zPosition.setEditable(true); JButton okButton = new JButton("OK"); chargeDataPanel.add(chargeLabel); chargeDataPanel.add(charge); chargeDataPanel.add(chargeModComboBox); chargeDataPanel.add(chargeUnitLabel); chargeDataPanel.add(xPositionLabel); chargeDataPanel.add(xPosition); chargeDataPanel.add(yPositionLabel); chargeDataPanel.add(yPosition); chargeDataPanel.add(okButton); chargeDataPanel.setMinimumSize(new Dimension(600, 100)); chargeDataPanel.setVisible(true); chargeDataFrame.add(chargeDataPanel); chargeDataFrame.setVisible(true); chargeDataFrame.setMinimumSize(new Dimension(600, 100)); xPosition.setText("0"); yPosition.setText("0"); charge.setText("0"); /* * okButton anonymous action listener takes the data entered into the JTextfields and creates point charges from it. */ okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //do { //chargesToCalc[okButtonPushes] = new PointCharge(Double.parseDouble(charge.getText()), Double.parseDouble(xPosition.getText()), Double.parseDouble(yPosition.getText())); int chargeModIndex = chargeModComboBox.getSelectedIndex(); DefaultValues.setChargeModIndex(chargeModIndex); chargeValue = Double.parseDouble(charge.getText()); xValue = Double.parseDouble(xPosition.getText()); yValue = Double.parseDouble(yPosition.getText()); chargesToCalc[okButtonPushes] = new PointCharge(chargeValue, xValue, yValue); charge.setText("0"); xPosition.setText("0"); yPosition.setText("0"); okButtonPushes++; chargeDataFrame.setTitle("Data For Charge #: " + (1 + okButtonPushes)); if (okButtonPushes == numberOfCharges) { confirm = JOptionPane.showConfirmDialog(null, "You have entered " + okButtonPushes + " charges. Press OK to confirm. \nPress Cancel to re-enter the charges", null, JOptionPane.OK_CANCEL_OPTION); if (confirm == JOptionPane.OK_OPTION) { DefaultValues.setCurrentPointCharges(chargesToCalc); ElectroStaticUIContainer.removeGraphFromdisplayPanel(); theCalculator = new CalculatorPanel(); calcVec = new VectorCalculator(mapper); volts = new VoltageAtPoint(mapper.getFieldPoints()); manGraph = new ManualPolygons(mapper); chart = manGraph.delaunayBuild(); drawVecs = new DrawElectricFieldLines(mapper); ElectroStaticUIContainer.add3DGraphToDisplayPanel(chart); ElectroStaticUIContainer.addVectorGraphToDisplayPanel(drawVecs.getChart()); setVectorChartToSave(); setChart3dToSave(); rotateIt = new ChartMouseController(chart); okButtonPushes = 0; chargeDataFrame.removeAll(); chargeDataFrame.dispose(); } else if (confirm == JOptionPane.CANCEL_OPTION) okButtonPushes = 0; } } //while(okButtonPushes < numberOfCharges); //} }); }
From source file:eu.apenet.dpt.standalone.gui.batch.ConvertAndValidateActionListener.java
public void actionPerformed(ActionEvent event) { labels = dataPreparationToolGUI.getLabels(); continueLoop = true;/*from w w w. jav a 2 s . c om*/ dataPreparationToolGUI.disableAllBtnAndItems(); dataPreparationToolGUI.disableEditionTab(); dataPreparationToolGUI.disableRadioButtons(); dataPreparationToolGUI.disableAllBatchBtns(); dataPreparationToolGUI.getAPEPanel().setFilename(""); final Object[] objects = dataPreparationToolGUI.getXmlEadList().getSelectedValues(); final ApexActionListener apexActionListener = this; new Thread(new Runnable() { public void run() { FileInstance uniqueFileInstance = null; String uniqueXslMessage = ""; int numberOfFiles = objects.length; int currentFileNumberBatch = 0; ProgressFrame progressFrame = new ProgressFrame(labels, parent, true, false, apexActionListener); JProgressBar batchProgressBar = progressFrame.getProgressBarBatch(); dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().disableConversionBtn(); dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().disableValidationBtn(); dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().disableConvertAndValidateBtn(); dataPreparationToolGUI.getXmlEadList().setEnabled(false); for (Object oneFile : objects) { if (!continueLoop) { break; } File file = (File) oneFile; FileInstance fileInstance = dataPreparationToolGUI.getFileInstances().get(file.getName()); if (numberOfFiles == 1) { uniqueFileInstance = fileInstance; } if (!fileInstance.isXml()) { fileInstance.setXml(XmlChecker.isXmlParseable(file) == null); if (!fileInstance.isXml()) { if (type == CONVERT || type == CONVERT_AND_VALIDATE) { fileInstance.setConversionErrors(labels.getString("conversion.error.fileNotXml")); } else if (type == VALIDATE || type == CONVERT_AND_VALIDATE) { fileInstance.setValidationErrors(labels.getString("validation.error.fileNotXml")); } dataPreparationToolGUI.enableSaveBtn(); dataPreparationToolGUI.enableRadioButtons(); dataPreparationToolGUI.enableEditionTab(); } } SummaryWorking summaryWorking = new SummaryWorking(dataPreparationToolGUI.getResultArea(), batchProgressBar); summaryWorking.setTotalNumberFiles(numberOfFiles); summaryWorking.setCurrentFileNumberBatch(currentFileNumberBatch); Thread threadRunner = new Thread(summaryWorking); threadRunner.setName(SummaryWorking.class.toString()); threadRunner.start(); JProgressBar progressBar = null; Thread threadProgress = null; CounterThread counterThread = null; CounterCLevelCall counterCLevelCall = null; if (fileInstance.isXml()) { currentFileNumberBatch = currentFileNumberBatch + 1; if (type == CONVERT || type == CONVERT_AND_VALIDATE) { dataPreparationToolGUI.setResultAreaText(labels.getString("converting") + " " + file.getName() + " (" + (currentFileNumberBatch) + "/" + numberOfFiles + ")"); String eadid = ""; boolean doTransformation = true; if (fileInstance.getValidationSchema() .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_SCHEMA.getPath())) || fileInstance.getValidationSchema().equals( Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAD_SCHEMA.getPath()))) { StaxTransformationTool staxTransformationTool = new StaxTransformationTool(file); staxTransformationTool.run(); LOG.debug("file has eadid? " + staxTransformationTool.isFileWithEadid()); if (!staxTransformationTool.isFileWithEadid()) { EadidQueryComponent eadidQueryComponent; if (staxTransformationTool.getUnitid() != null && !staxTransformationTool.getUnitid().equals("")) { eadidQueryComponent = new EadidQueryComponent( staxTransformationTool.getUnitid()); } else { eadidQueryComponent = new EadidQueryComponent(labels); } int result = JOptionPane.showConfirmDialog(parent, eadidQueryComponent.getMainPanel(), labels.getString("enterEADID"), JOptionPane.OK_CANCEL_OPTION); while (StringUtils.isEmpty(eadidQueryComponent.getEntryEadid()) && result != JOptionPane.CANCEL_OPTION) { result = JOptionPane.showConfirmDialog(parent, eadidQueryComponent.getMainPanel(), labels.getString("enterEADID"), JOptionPane.OK_CANCEL_OPTION); } if (result == JOptionPane.OK_OPTION) { eadid = eadidQueryComponent.getEntryEadid(); } else if (result == JOptionPane.CANCEL_OPTION) { doTransformation = false; } } } if (doTransformation) { int counterMax = 0; if (fileInstance.getConversionScriptName() .equals(Utilities.XSL_DEFAULT_APEEAD_NAME)) { progressBar = progressFrame.getProgressBarSingle(); progressBar.setVisible(true); progressFrame .setTitle(labels.getString("progressTrans") + " - " + file.getName()); CountCLevels countCLevels = new CountCLevels(); counterMax = countCLevels.countOneFile(file); if (counterMax > 0) { counterCLevelCall = new CounterCLevelCall(); counterCLevelCall.initializeCounter(counterMax); counterThread = new CounterThread(counterCLevelCall, progressBar, counterMax); threadProgress = new Thread(counterThread); threadProgress.setName(CounterThread.class.toString()); threadProgress.start(); } } try { try { File xslFile = new File(fileInstance.getConversionScriptPath()); File outputFile = new File(Utilities.TEMP_DIR + "temp_" + file.getName()); outputFile.deleteOnExit(); StringWriter xslMessages; HashMap<String, String> parameters = dataPreparationToolGUI.getParams(); parameters.put("eadidmissing", eadid); CheckIsEadFile checkIsEadFile = new CheckIsEadFile(file); checkIsEadFile.run(); if (checkIsEadFile.isEadRoot()) { File outputFile_temp = new File( Utilities.TEMP_DIR + ".temp_" + file.getName()); TransformationTool.createTransformation(FileUtils.openInputStream(file), outputFile_temp, Utilities.BEFORE_XSL_FILE, null, true, true, null, true, null); xslMessages = TransformationTool.createTransformation( FileUtils.openInputStream(outputFile_temp), outputFile, xslFile, parameters, true, true, null, true, counterCLevelCall); outputFile_temp.delete(); } else { xslMessages = TransformationTool.createTransformation( FileUtils.openInputStream(file), outputFile, xslFile, parameters, true, true, null, true, null); } fileInstance.setConversionErrors(xslMessages.toString()); fileInstance .setCurrentLocation(Utilities.TEMP_DIR + "temp_" + file.getName()); fileInstance.setConverted(); fileInstance.setLastOperation(FileInstance.Operation.CONVERT); uniqueXslMessage = xslMessages.toString(); if (xslMessages.toString().equals("")) { if (fileInstance.getConversionScriptName() .equals(Utilities.XSL_DEFAULT_APEEAD_NAME)) { fileInstance.setConversionErrors( labels.getString("conversion.noExcludedElements")); } else { fileInstance.setConversionErrors( labels.getString("conversion.finished")); } } if (!continueLoop) { break; } } catch (Exception e) { fileInstance.setConversionErrors(labels.getString("conversionException") + "\r\n\r\n-------------\r\n" + e.getMessage()); throw new Exception("Error when converting " + file.getName(), e); } if (threadProgress != null) { counterThread.stop(); threadProgress.interrupt(); } if (progressBar != null) { if (counterMax > 0) { progressBar.setValue(counterMax); } progressBar.setIndeterminate(true); } } catch (Exception e) { LOG.error("Error when converting and validating", e); } finally { summaryWorking.stop(); threadRunner.interrupt(); dataPreparationToolGUI.getXmlEadListLabel().repaint(); dataPreparationToolGUI.getXmlEadList().repaint(); if (progressBar != null) { progressBar.setVisible(false); } } } if (numberOfFiles == 1) { uniqueFileInstance = fileInstance; } } if (type == VALIDATE || type == CONVERT_AND_VALIDATE) { try { try { File fileToValidate = new File(fileInstance.getCurrentLocation()); InputStream is = FileUtils.openInputStream(fileToValidate); dataPreparationToolGUI .setResultAreaText(labels.getString("validating") + " " + file.getName() + " (" + currentFileNumberBatch + "/" + numberOfFiles + ")"); XsdObject xsdObject = fileInstance.getValidationSchema(); List<SAXParseException> exceptions; if (xsdObject.getName().equals(Xsd_enum.DTD_EAD_2002.getReadableName())) { exceptions = DocumentValidation.xmlValidationAgainstDtd( fileToValidate.getAbsolutePath(), Utilities.getUrlPathXsd(xsdObject)); } else { exceptions = DocumentValidation.xmlValidation(is, Utilities.getUrlPathXsd(xsdObject), xsdObject.isXsd11()); } if (exceptions == null || exceptions.isEmpty()) { fileInstance.setValid(true); fileInstance.setValidationErrors(labels.getString("validationSuccess")); if (xsdObject.getFileType().equals(FileInstance.FileType.EAD) && xsdObject.getName().equals("apeEAD")) { XmlQualityCheckerCall xmlQualityCheckerCall = new XmlQualityCheckerCall(); InputStream is2 = FileUtils .openInputStream(new File(fileInstance.getCurrentLocation())); TransformationTool.createTransformation(is2, null, Utilities.XML_QUALITY_FILE, null, true, true, null, false, xmlQualityCheckerCall); String xmlQualityStr = createXmlQualityString(xmlQualityCheckerCall); fileInstance.setValidationErrors( fileInstance.getValidationErrors() + xmlQualityStr); fileInstance.setXmlQualityErrors( createXmlQualityErrors(xmlQualityCheckerCall)); } } else { String errors = Utilities.stringFromList(exceptions); fileInstance.setValidationErrors(errors); fileInstance.setValid(false); } fileInstance.setLastOperation(FileInstance.Operation.VALIDATE); } catch (Exception ex) { fileInstance.setValid(false); fileInstance.setValidationErrors(labels.getString("validationException") + "\r\n\r\n-------------\r\n" + ex.getMessage()); throw new Exception("Error when validating", ex); } } catch (Exception e) { LOG.error("Error when validating", e); } finally { summaryWorking.stop(); threadRunner.interrupt(); dataPreparationToolGUI.getXmlEadListLabel().repaint(); dataPreparationToolGUI.getXmlEadList().repaint(); if (progressBar != null) { progressBar.setVisible(false); } } if (numberOfFiles == 1) { uniqueFileInstance = fileInstance; } } } } Toolkit.getDefaultToolkit().beep(); if (progressFrame != null) { try { progressFrame.stop(); } catch (Exception e) { LOG.error("Error when stopping the progress bar", e); } } dataPreparationToolGUI.getFinalAct().run(); if (numberOfFiles > 1) { dataPreparationToolGUI.getXmlEadList().clearSelection(); } else if (uniqueFileInstance != null) { if (type != VALIDATE) { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .setConversionErrorText(replaceGtAndLt(uniqueFileInstance.getConversionErrors())); if (uniqueXslMessage.equals("")) { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .checkFlashingTab(APETabbedPane.TAB_CONVERSION, Utilities.FLASHING_GREEN_COLOR); } else { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .checkFlashingTab(APETabbedPane.TAB_CONVERSION, Utilities.FLASHING_RED_COLOR); } } if (type != CONVERT) { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .setValidationErrorText(uniqueFileInstance.getValidationErrors()); if (uniqueFileInstance.isValid()) { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .checkFlashingTab(APETabbedPane.TAB_VALIDATION, Utilities.FLASHING_GREEN_COLOR); if (uniqueFileInstance.getValidationSchema() .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_SCHEMA.getPath()))) { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableConversionEdmBtn(); dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableValidationReportBtn(); } else if (uniqueFileInstance.getValidationSchema() .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAD_SCHEMA.getPath())) || uniqueFileInstance.getValidationSchema() .equals(Utilities.getXsdObjectFromPath(Xsd_enum.DTD_EAD_2002.getPath())) || uniqueFileInstance.getValidationSchema().equals( Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAC_SCHEMA.getPath()))) { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableConversionBtn(); // dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableValidationReportBtn(); } } else { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .checkFlashingTab(APETabbedPane.TAB_VALIDATION, Utilities.FLASHING_RED_COLOR); if (uniqueFileInstance.getValidationSchema() .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_SCHEMA.getPath())) || uniqueFileInstance.getValidationSchema().equals( Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAD_SCHEMA.getPath())) || uniqueFileInstance.getValidationSchema() .equals(Utilities.getXsdObjectFromPath(Xsd_enum.DTD_EAD_2002.getPath())) || uniqueFileInstance.getValidationSchema().equals( Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_EAC_SCHEMA.getPath())) || uniqueFileInstance.getValidationSchema().equals( Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAC_SCHEMA.getPath()))) { dataPreparationToolGUI.enableConversionBtns(); dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .enableConvertAndValidateBtn(); } } } dataPreparationToolGUI.enableMessageReportBtns(); } if (continueLoop) { dataPreparationToolGUI.setResultAreaText(labels.getString("finished")); } else { dataPreparationToolGUI.setResultAreaText(labels.getString("aborted")); } dataPreparationToolGUI.enableSaveBtn(); if (type == CONVERT) { dataPreparationToolGUI.enableValidationBtns(); } dataPreparationToolGUI.enableRadioButtons(); dataPreparationToolGUI.enableEditionTab(); } }).start(); }
From source file:com.opendoorlogistics.studio.scripts.list.ScriptsPanel.java
private List<MyAction> createActions(AppPermissions appPermissions) { ArrayList<MyAction> ret = new ArrayList<>(); if (appPermissions.isScriptEditingAllowed()) { ret.add(new MyAction(SimpleActionConfig.addItem.setItemName("script"), false, false, false) { @Override//from w ww. ja va 2s. c om public void actionPerformed(ActionEvent e) { Script script = new SetupComponentWizard(SwingUtilities.getWindowAncestor(ScriptsPanel.this), api, scriptUIManager.getAvailableFieldsQuery()).showModal(); // Script script =new ScriptWizardActions(api,SwingUtilities.getWindowAncestor(ScriptsPanel.this)).promptUser(); if (script != null) { scriptUIManager.launchScriptEditor(script, null, isOkDirectory() ? directory : null); } } }); ret.add(new MyAction(SimpleActionConfig.editItem.setItemName("script"), false, false, true) { @Override public void actionPerformed(ActionEvent e) { ScriptNode node = scriptsTree.getSelectedValue(); if (node != null && node.isAvailable()) { ScriptsPanel.this.scriptUIManager.launchScriptEditor(node.getFile(), node.getLaunchEditorId()); } } }); ret.add(new MyAction(SimpleActionConfig.deleteItem.setItemName("script"), false, false, false) { @Override public void actionPerformed(ActionEvent e) { ScriptNode node = scriptsTree.getSelectedValue(); if (node == null) { return; } if (JOptionPane.showConfirmDialog(ScriptsPanel.this, "Really delete script " + node.getFile().getName() + " from disk?", "Delete script", JOptionPane.YES_NO_OPTION) == JOptionPane.OK_OPTION) { if (!node.getFile().delete()) { JOptionPane.showMessageDialog(ScriptsPanel.this, "Could not delete file"); } else { onDirectoryChanged(directory); } } } @Override public void updateEnabledState() { ScriptNode selected = scriptsTree.getSelectedValue(); boolean enabled = true; if (selected == null) { enabled = false; } if (enabled && selected.isScriptRoot() == false) { // can only delete the root enabled = false; } setEnabled(enabled); } }); ret.add(new MyAction(SimpleActionConfig.testCompileScript, true, false, true) { @Override public void actionPerformed(ActionEvent e) { ScriptNode node = scriptsTree.getSelectedValue(); if (node != null) { scriptUIManager.testCompileScript(node.getFile(), node.getLaunchExecutorId()); } } }); ret.add(new MyAction(SimpleActionConfig.runScript, true, true, true) { @Override public void actionPerformed(ActionEvent e) { ScriptNode node = scriptsTree.getSelectedValue(); if (node != null) { scriptUIManager.executeScript(node.getFile(), node.getLaunchExecutorId()); } } @Override public void updateEnabledState() { setEnabled(ScriptNode.isRunnable(scriptsTree.getSelectedValue(), scriptUIManager)); } }); } return ret; }
From source file:de.unibayreuth.bayeos.goat.panels.timeseries.JPanelChart.java
/** * Handles an action event.//from w w w.j a v a 2s . c o m * * @param evt * the event. */ public void actionPerformed(ActionEvent evt) { try { String acmd = evt.getActionCommand(); if (acmd.equals(ACTION_CHART_ZOOM_BOX)) { setPanMode(false); } else if (acmd.equals(ACTION_CHART_PAN)) { setPanMode(true); } else if (acmd.equals(ACTION_CHART_ZOOM_IN)) { ChartRenderingInfo info = this.chartPanel.getChartRenderingInfo(); Rectangle2D rect = info.getPlotInfo().getDataArea(); zoomBoth(rect.getCenterX(), rect.getCenterY(), ZOOM_FACTOR); } else if (acmd.equals(ACTION_CHART_ZOOM_OUT)) { ChartRenderingInfo info = this.chartPanel.getChartRenderingInfo(); Rectangle2D rect = info.getPlotInfo().getDataArea(); zoomBoth(rect.getCenterX(), rect.getCenterY(), 1 / ZOOM_FACTOR); } else if (acmd.equals(ACTION_CHART_ZOOM_TO_FIT)) { // X-axis (has no fixed borders) chartPanel.autoRangeHorizontal(); Plot plot = chartPanel.getChart().getPlot(); if (plot instanceof ValueAxisPlot) { XYPlot vvPlot = (XYPlot) plot; ValueAxis axis = vvPlot.getRangeAxis(); if (axis != null) { axis.setLowerBound(yMin); axis.setUpperBound(yMax); } } } else if (acmd.equals(ACTION_CHART_EXPORT)) { try { chartPanel.doSaveAs(); } catch (IOException i) { MsgBox.error(i.getMessage()); } } else if (acmd.equals(ACTION_CHART_PRINT)) { chartPanel.createChartPrintJob(); } else if (acmd.equals(ACTION_CHART_PROPERTIES)) { ChartPropertyEditPanel panel = new ChartPropertyEditPanel(jFreeChart); int result = JOptionPane.showConfirmDialog(this, panel, localizationResources.getString("Chart_Properties"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { panel.updateChartProperties(jFreeChart); } } } catch (Exception e) { MsgBox.error(e.getMessage()); } }
From source file:sk.uniza.fri.pds.spotreba.energie.gui.MainGui.java
private void showSpendingStatisticsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showSpendingStatisticsActionPerformed final SpendingStatisticsParameters params = new SpendingStatisticsParameters(); int option = showUniversalInputDialog(params, "Vvoj spotreby"); if (option == JOptionPane.OK_OPTION) { new SwingWorker<List, RuntimeException>() { @Override/*w w w .j av a 2 s .co m*/ protected List doInBackground() throws Exception { try { return SeHistoriaService.getInstance().getSpendingStatistics(params); } catch (RuntimeException e) { publish(e); return null; } } @Override protected void done() { try { List<KrokSpotreby> spendingStatistics = get(); if (spendingStatistics != null) { final TimeSeries series = new TimeSeries(""); final String title = "Vvoj spotreby"; for (KrokSpotreby krok : spendingStatistics) { series.add(new Month(krok.getDatumOd()), krok.getSpotreba()); } final IntervalXYDataset dataset = (IntervalXYDataset) new TimeSeriesCollection(series); JFreeChart chart = ChartFactory.createXYBarChart(title, // title "", // x-axis label true, // date axis? "", // y-axis label dataset, // data PlotOrientation.VERTICAL, // orientation false, // create legend? true, // generate tooltips? false // generate URLs? ); // Set date axis style DateAxis axis = (DateAxis) ((XYPlot) chart.getPlot()).getDomainAxis(); axis.setDateFormatOverride(new SimpleDateFormat("yyyy")); DateFormat formatter = new SimpleDateFormat("yyyy"); DateTickUnit unit = new DateTickUnit(DateTickUnitType.YEAR, 1, formatter); axis.setTickUnit(unit); JOptionPane.showMessageDialog(null, new ChartPanel(chart)); } } catch (InterruptedException | ExecutionException ex) { Logger.getLogger(MainGui.class.getName()).log(Level.SEVERE, null, ex); } } @Override protected void process(List<RuntimeException> chunks) { if (chunks.size() > 0) { showException("Chyba", chunks.get(0)); } } }.execute(); } }
From source file:ch.admin.hermes.etl.load.HermesETLApplication.java
/** * CommandLine parse und fehlende Argumente verlangen * @param args Args//from w w w . ja va 2 s . c o m * @throws ParseException */ private static void parseCommandLine(String[] args) throws Exception { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // HACK um UTF-8 CharSet fuer alle Dateien zu setzen (http://stackoverflow.com/questions/361975/setting-the-default-java-character-encoding) System.setProperty("file.encoding", "UTF-8"); Field charset = Charset.class.getDeclaredField("defaultCharset"); charset.setAccessible(true); charset.set(null, null); // commandline Options - FremdsystemSite, Username und Password Options options = new Options(); options.addOption("s", true, "Zielsystem - URL"); options.addOption("u", true, "Zielsystem - Username"); options.addOption("p", true, "Zielsystem - Password"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); site = cmd.getOptionValue("s"); user = cmd.getOptionValue("u"); passwd = cmd.getOptionValue("p"); // restliche Argumente pruefen - sonst usage ausgeben String[] others = cmd.getArgs(); if (others.length >= 1 && (others[0].endsWith(".js") || others[0].endsWith(".ftl"))) script = others[0]; if (others.length >= 2 && others[1].endsWith(".xml")) model = others[1]; // Dialog mit allen Werten zusammenstellen JComboBox<String> scenarios = new JComboBox<String>(crawler.getScenarios()); JTextField tsite = new JTextField(45); tsite.setText(site); JTextField tuser = new JTextField(16); tuser.setText(user); JPasswordField tpasswd = new JPasswordField(16); tpasswd.setText(passwd); final JTextField tscript = new JTextField(45); tscript.setText(script); final JTextField tmodel = new JTextField(45); tmodel.setText(model); JPanel myPanel = new JPanel(new GridLayout(6, 2)); myPanel.add(new JLabel("Szenario (von http://www.hermes.admin.ch):")); myPanel.add(scenarios); myPanel.add(new JLabel("XML Model:")); myPanel.add(tmodel); JPanel pmodel = new JPanel(); pmodel.add(tmodel); JButton bmodel = new JButton("..."); pmodel.add(bmodel); bmodel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { model = getFile("Szenario XML Model", new String[] { "XML Model" }, new String[] { ".xml" }); if (model != null) tmodel.setText(model); } }); myPanel.add(pmodel); scenarios.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { try { Object o = e.getItem(); tmodel.setText(crawler.getModelURL(o.toString())); scenario = o.toString(); } catch (Exception e1) { } } }); // Script myPanel.add(new JLabel("Umwandlungs-Script:")); JPanel pscript = new JPanel(); pscript.add(tscript); JButton bscript = new JButton("..."); pscript.add(bscript); myPanel.add(pscript); bscript.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { script = getFile("JavaScript/Freemarker Umwandlungs-Script", new String[] { "JavaScript", "Freemarker" }, new String[] { ".js", ".ftl" }); if (script != null) tscript.setText(script); } }); // Zielsystem Angaben myPanel.add(new JLabel("Zielsystem URL:")); myPanel.add(tsite); myPanel.add(new JLabel("Zielsystem Benutzer:")); myPanel.add(tuser); myPanel.add(new JLabel("Zielsystem Password:")); myPanel.add(tpasswd); // Trick um Feld scenario und model zu setzen. if (scenarios.getItemCount() >= 8) scenarios.setSelectedIndex(8); // Dialog int result = JOptionPane.showConfirmDialog(null, myPanel, "HERMES 5 XML Model nach Fremdsystem/Format", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { site = tsite.getText(); user = tuser.getText(); passwd = new String(tpasswd.getPassword()); model = tmodel.getText(); script = tscript.getText(); } else System.exit(1); if (model == null || script == null || script.trim().length() == 0) usage(); if (script.endsWith(".js")) if (site == null || user == null || passwd == null || user.trim().length() == 0 || passwd.trim().length() == 0) usage(); }