List of usage examples for javax.swing JFileChooser setCurrentDirectory
@BeanProperty(preferred = true, description = "The directory that the JFileChooser is showing files of.") public void setCurrentDirectory(File dir)
From source file:com.commander4j.db.JDBUserReport.java
private String promptUserforSave() { JFileChooser saveTYPE = new JFileChooser(); String filename = getExportFilename(); if (isPromptSaveAsRequired()) { try {//from w ww . j a va2s.c o m File f = new File(new File(getExportFilename()).getCanonicalPath()); saveTYPE.setCurrentDirectory(f); if (getDestination().equals("EXCEL")) saveTYPE.addChoosableFileFilter(new JFileFilterXLS()); if (getDestination().equals("JASPER_REPORT")) saveTYPE.addChoosableFileFilter(new JFileFilterPDF()); if (getDestination().equals("PDF")) saveTYPE.addChoosableFileFilter(new JFileFilterPDF()); if (getDestination().equals("CSV")) saveTYPE.addChoosableFileFilter(new JFileFilterCSV()); if (getDestination().equals("ACCESS")) saveTYPE.addChoosableFileFilter(new JFileFilterMDB()); saveTYPE.setSelectedFile(new File(getExportFilename())); int result = saveTYPE.showSaveDialog(Common.mainForm); if (result == 0) { File selectedFile; selectedFile = saveTYPE.getSelectedFile(); if (selectedFile != null) { filename = selectedFile.getAbsolutePath(); } } } catch (Exception ex) { } } return filename; }
From source file:ffx.ui.KeywordPanel.java
/** * Give the user a File Dialog Box so they can select a key file. *//*from w w w.j av a 2 s . c om*/ public void keyOpen() { if (fileOpen && KeywordComponent.isKeywordModified()) { int option = JOptionPane.showConfirmDialog(this, "Save Changes First", "Opening New File", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE); if (option == JOptionPane.CANCEL_OPTION) { return; } else if (option == JOptionPane.YES_OPTION) { keySave(currentKeyFile); } keyClear(); } JFileChooser d = MainPanel.resetFileChooser(); if (currentSystem != null) { File cwd = currentSystem.getFile(); if (cwd != null && cwd.getParentFile() != null) { d.setCurrentDirectory(cwd.getParentFile()); } } d.setAcceptAllFileFilterUsed(false); d.setFileFilter(MainPanel.keyFileFilter); d.setDialogTitle("Open KEY File"); int result = d.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { File newKeyFile = d.getSelectedFile(); if (newKeyFile != null && newKeyFile.exists() && newKeyFile.canRead()) { keyOpen(newKeyFile); } } }
From source file:ir.ac.iust.nlp.postagger.POSTaggerForm.java
private String showFileDialog(String currentDir, boolean isFolder, FileNameExtensionFilter filter) { JFileChooser fc = new JFileChooser(); if (currentDir.length() == 0) { fc.setCurrentDirectory(new java.io.File(".")); } else {//from w w w . j a v a 2 s . co m fc.setCurrentDirectory(new java.io.File(currentDir)); } fc.setMultiSelectionEnabled(false); if (filter != null) { fc.setFileFilter(filter); } String title = "Select File"; if (isFolder == true) { fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); title = "Select Folder"; } if (fc.showDialog(this, title) == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String path = file.getPath(); if (isFolder == true && path.lastIndexOf(File.separator) != path.length() - 1) { path = path + File.separator; } return path; } else { return currentDir; } }
From source file:com.lp.client.frame.component.PanelDokumentenablage.java
private boolean chooseFile() throws Throwable { final JFileChooser fc = new JFileChooser(); if (defaultEinlesePfad != null) { fc.setCurrentDirectory(new File(defaultEinlesePfad)); }//from w w w. j ava 2 s . c o m int retVal = fc.showOpenDialog(this); if (retVal == JFileChooser.APPROVE_OPTION) { file = fc.getSelectedFile(); try { wmcMedia.setOMedia(Helper.getBytesFromFile(file)); return true; } catch (IOException e) { return false; } catch (Throwable e) { return false; } } else { return false; } }
From source file:edu.harvard.mcz.imagecapture.jobs.JobSingleBarcodeScan.java
@Override public void start() { startDate = new Date(); Singleton.getSingletonInstance().getJobList().addJob((RunnableJob) this); setPercentComplete(0);/* w ww . ja va2 s . c o m*/ Singleton.getSingletonInstance().getMainFrame().setStatusMessage("Selecting file to check."); String rawOCR = ""; // to hold unparsed ocr output from unit tray label //Create a file chooser final JFileChooser fileChooser = new JFileChooser(); if (Singleton.getSingletonInstance().getProperties().getProperties() .getProperty(ImageCaptureProperties.KEY_LASTPATH) != null) { fileChooser.setCurrentDirectory(new File(Singleton.getSingletonInstance().getProperties() .getProperties().getProperty(ImageCaptureProperties.KEY_LASTPATH))); } //FileNameExtensionFilter filter = new FileNameExtensionFilter("TIFF Images", "tif", "tiff"); FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files", "tif", "tiff", "jpg", "jpeg", "png"); fileChooser.setFileFilter(filter); int returnValue = fileChooser.showOpenDialog(Singleton.getSingletonInstance().getMainFrame()); setPercentComplete(10); Singleton.getSingletonInstance().getMainFrame().setStatusMessage("Scanning file for barcode."); if (returnValue == JFileChooser.APPROVE_OPTION) { File fileToCheck = fileChooser.getSelectedFile(); Singleton.getSingletonInstance().getProperties().getProperties() .setProperty(ImageCaptureProperties.KEY_LASTPATH, fileToCheck.getPath()); String filename = fileToCheck.getName(); log.debug("Selected file " + filename + " to scan for barcodes"); CandidateImageFile.debugCheckHeightWidth(fileToCheck); // scan selected file PositionTemplate defaultTemplate = null; // Figure out which template to use. DefaultPositionTemplateDetector detector = new DefaultPositionTemplateDetector(); String template = ""; try { template = detector.detectTemplateForImage(fileToCheck); } catch (UnreadableFileException e3) { // TODO Auto-generated catch block e3.printStackTrace(); } setPercentComplete(20); try { defaultTemplate = new PositionTemplate(template); log.debug("Set template to: " + defaultTemplate.getTemplateId()); } catch (NoSuchTemplateException e1) { try { defaultTemplate = new PositionTemplate(PositionTemplate.TEMPLATE_DEFAULT); log.error("Template not recongised, reset template to: " + defaultTemplate.getTemplateId()); } catch (Exception e2) { // We shouldn't end up here - we just asked for the default template by its constant. log.fatal("PositionTemplate doesn't recognize TEMPLATE_DEFAULT"); log.trace(e2); ImageCaptureApp.exit(ImageCaptureApp.EXIT_ERROR); } } // TODO: Store the template id for this image with the other image metadata so // that we don't have to check again. CandidateImageFile scannableFile; try { scannableFile = new CandidateImageFile(fileToCheck, defaultTemplate); String barcode = scannableFile.getBarcodeTextAtFoundTemplate(); if (scannableFile.getCatalogNumberBarcodeStatus() != CandidateImageFile.RESULT_BARCODE_SCANNED) { log.error("Error scanning for barcode: " + barcode); barcode = ""; } String exifComment = scannableFile.getExifUserCommentText(); if (barcode.equals("") && Singleton.getSingletonInstance().getBarcodeMatcher().matchesPattern(exifComment)) { // There should be a template for this image, and it shouldn't be the TEMPLATE_NO_COMPONENT_PARTS if (defaultTemplate.getTemplateId().equals(PositionTemplate.TEMPLATE_NO_COMPONENT_PARTS)) { try { // This will give us a shot at OCR of the text and display of the image parts. defaultTemplate = new PositionTemplate(PositionTemplate.TEMPLATE_DEFAULT); log.error("Barcode not recongised, but exif contains barcode, reset template to: " + defaultTemplate.getTemplateId()); } catch (Exception e2) { // We shouldn't end up here - we just asked for the default template by its constant. log.fatal("PositionTemplate doesn't recognize TEMPLATE_DEFAULT"); log.trace(e2); ImageCaptureApp.exit(ImageCaptureApp.EXIT_ERROR); } } } log.debug("With template:" + defaultTemplate.getTemplateId()); log.debug("Barcode=" + barcode); setPercentComplete(30); String warning = ""; if (Singleton.getSingletonInstance().getProperties().getProperties() .getProperty(ImageCaptureProperties.KEY_REDUNDANT_COMMENT_BARCODE).equals("true")) { if (!barcode.equals(exifComment)) { warning = "Warning: non-matching QR code barcode and exif Comment"; System.out.println(warning); } } Singleton.getSingletonInstance().getMainFrame().setStatusMessage("Loading image."); ImageDisplayFrame resultFrame = new ImageDisplayFrame(); if (Singleton.getSingletonInstance().getProperties().getProperties() .getProperty(ImageCaptureProperties.KEY_REDUNDANT_COMMENT_BARCODE).equals("true")) { resultFrame.setBarcode("QR=" + barcode + " Comment=" + exifComment + " " + warning); } else { resultFrame.setBarcode("QR=" + barcode); } try { resultFrame.loadImagesFromFile(fileToCheck, defaultTemplate, null); } catch (ImageLoadException e2) { System.out.println("Error loading image file."); System.out.println(e2.getMessage()); } catch (BadTemplateException e2) { System.out.println("Template doesn't match image file."); System.out.println(e2.getMessage()); try { try { try { template = detector.detectTemplateForImage(fileToCheck); } catch (UnreadableFileException e3) { // TODO Auto-generated catch block e3.printStackTrace(); } defaultTemplate = new PositionTemplate(template); } catch (NoSuchTemplateException e) { // TODO Auto-generated catch block e.printStackTrace(); } resultFrame.loadImagesFromFile(fileToCheck, defaultTemplate, null); } catch (ImageLoadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (BadTemplateException e) { System.out.println("Template doesn't match image file."); System.out.println(e2.getMessage()); } } UnitTrayLabel labelRead = null; try { // Read unitTrayLabelBarcode, failover to OCR and parse UnitTray Label rawOCR = ""; labelRead = scannableFile.getTaxonLabelQRText(defaultTemplate); if (labelRead == null) { try { labelRead = scannableFile.getTaxonLabelQRText(new PositionTemplate("Test template 2")); } catch (NoSuchTemplateException e1) { try { labelRead = scannableFile .getTaxonLabelQRText(new PositionTemplate("Small template 2")); } catch (NoSuchTemplateException e2) { log.error("None of " + defaultTemplate.getName() + " Test template 2 or Small template 2 were found"); } } } else { log.debug("Translated UnitTrayBarcode to: " + labelRead.toJSONString()); } if (labelRead != null) { rawOCR = labelRead.toJSONString(); } else { log.debug("Failing over to OCR with tesseract"); rawOCR = scannableFile.getLabelOCRText(defaultTemplate); } log.debug(rawOCR); resultFrame.setRawOCRLabel(rawOCR); setPercentComplete(40); } catch (Exception ex) { System.out.println(ex.getMessage()); } setPercentComplete(50); resultFrame.pack(); resultFrame.setVisible(true); resultFrame.centerSpecimen(); resultFrame.center(); setPercentComplete(60); if (persist) { // Check that fileToCheck is within imagebase. if (!ImageCaptureProperties.isInPathBelowBase(fileToCheck)) { String base = Singleton.getSingletonInstance().getProperties().getProperties() .getProperty(ImageCaptureProperties.KEY_IMAGEBASE); log.error("Tried to scan file (" + fileToCheck.getPath() + ") outside of base image directory (" + base + ")"); throw new UnreadableFileException( "Can't scan and database files outside of base image directory (" + base + ")"); } String state = WorkFlowStatus.STAGE_0; Singleton.getSingletonInstance().getMainFrame().setStatusMessage("Connecting to database."); // try to parse the raw OCR TaxonNameReturner parser = null; if (labelRead != null) { rawOCR = labelRead.toJSONString(); state = WorkFlowStatus.STAGE_1; parser = (TaxonNameReturner) labelRead; } else { log.debug("Failing over to OCR with tesseract"); rawOCR = scannableFile.getLabelOCRText(defaultTemplate); state = WorkFlowStatus.STAGE_0; parser = new UnitTrayLabelParser(rawOCR); } // Case 1: This is an image of papers associated with a container (a unit tray or a box). // This case can be identified by there being no barcode data associated with the image. // Action: // A) Check the exifComment to see what metadata is there, if blank, bring up a dialog. // Options: A drawer, for which number is captured. A unit tray, capture ?????????. A specimen // where barcode wasn't read, allow capture of barcode and treat as Case 2. // B) Create an image record and store the image metadata (with a null specimen_id). boolean isSpecimenImage = false; boolean isDrawerImage = false; // Test: is exifComment a barcode: if (Singleton.getSingletonInstance().getBarcodeMatcher().matchesPattern(exifComment) || Singleton.getSingletonInstance().getBarcodeMatcher().matchesPattern(barcode)) { isSpecimenImage = true; System.out.println("Specimen Image"); } else { if (exifComment.matches(Singleton.getSingletonInstance().getProperties().getProperties() .getProperty(ImageCaptureProperties.KEY_REGEX_DRAWERNUMBER))) { isDrawerImage = true; System.out.println("Drawer Image"); } else { // Ask. System.out.println("Need to ask."); WhatsThisImageDialog askDialog = new WhatsThisImageDialog(resultFrame, fileToCheck); askDialog.setVisible(true); if (askDialog.isSpecimen()) { isSpecimenImage = true; exifComment = askDialog.getBarcode(); } if (askDialog.isDrawerImage()) { isDrawerImage = true; exifComment = askDialog.getDrawerNumber(); } } } // applies to both cases. ICImageLifeCycle imageCont = new ICImageLifeCycle(); ICImage tryMe = new ICImage(); tryMe.setFilename(filename); //String path = fileToCheck.getParentFile().getPath(); String path = ImageCaptureProperties.getPathBelowBase(fileToCheck); //String[] bits = rawOCR.split(":"); List<ICImage> matches = imageCont.findByExample(tryMe); // Case 2: This is an image of a specimen and associated labels or an image assocated with // a specimen with the specimen's barcode label in the image. // This case can be identified by there being a barcode in a templated position or there // being a barcode in the exif comment tag. // Action: // A) Check if a specimen record exists, if not, create one from the barcode and OCR data. // B) Create an image record and store the image metadata. // Handle a potential failure case, existing image record without a linked specimen, but which // should have one. if (matches.size() == 1 && isSpecimenImage) { ICImage existing = imageCont.findById(matches.get(0).getImageId()); if (existing.getSpecimen() == null) { // If the existing image record has no attached specimen, delete it. // We will create it again from tryMe. try { Singleton.getSingletonInstance().getMainFrame() .setStatusMessage("Removing existing unlinked image record."); imageCont.delete(existing); matches.remove(0); } catch (SaveFailedException e) { log.error(e.getMessage(), e); } } } if (matches.size() == 0) { String rawBarcode = barcode; if (isSpecimenImage) { Singleton.getSingletonInstance().getMainFrame() .setStatusMessage("Creating new specimen record."); Specimen s = new Specimen(); if ((!Singleton.getSingletonInstance().getBarcodeMatcher().matchesPattern(barcode)) && Singleton.getSingletonInstance().getBarcodeMatcher() .matchesPattern(exifComment)) { s.setBarcode(exifComment); barcode = exifComment; } else { if (!Singleton.getSingletonInstance().getBarcodeMatcher().matchesPattern(barcode)) { // Won't be able to save the specimen record if we end up here. log.error( "Neither exifComment nor QR Code barcode match the expected pattern for a barcode, but isSpecimenImage got set to true."); } s.setBarcode(barcode); } s.setWorkFlowStatus(state); if (!state.equals(WorkFlowStatus.STAGE_0)) { s.setFamily(parser.getFamily()); s.setSubfamily(parser.getSubfamily()); s.setTribe(parser.getTribe()); } else { s.setFamily(""); // Look up likely matches for the OCR of the higher taxa in the HigherTaxon authority file. HigherTaxonLifeCycle hls = new HigherTaxonLifeCycle(); if (parser.getTribe().trim().equals("")) { if (hls.isMatched(parser.getFamily(), parser.getSubfamily())) { // If there is a match, use it. String[] higher = hls.findMatch(parser.getFamily(), parser.getSubfamily()); s.setFamily(higher[0]); s.setSubfamily(higher[1]); } else { // otherwise use the raw OCR output. s.setFamily(parser.getFamily()); s.setSubfamily(parser.getSubfamily()); } s.setTribe(""); } else { if (hls.isMatched(parser.getFamily(), parser.getSubfamily(), parser.getTribe())) { String[] higher = hls.findMatch(parser.getFamily(), parser.getSubfamily(), parser.getTribe()); s.setFamily(higher[0]); s.setSubfamily(higher[1]); s.setTribe(higher[2]); } else { s.setFamily(parser.getFamily()); s.setSubfamily(parser.getSubfamily()); s.setTribe(parser.getTribe()); } } if (!parser.getFamily().equals("")) { // check family against database (with a soundex match) String match = hls.findMatch(parser.getFamily()); if (match != null && !match.trim().equals("")) { s.setFamily(match); } } } // trim family to fit (in case multiple parts of taxon name weren't parsed // and got concatenated into family field. if (s.getFamily().length() > 40) { s.setFamily(s.getFamily().substring(0, 40)); } s.setGenus(parser.getGenus()); s.setSpecificEpithet(parser.getSpecificEpithet()); s.setSubspecificEpithet(parser.getSubspecificEpithet()); s.setInfraspecificEpithet(parser.getInfraspecificEpithet()); s.setInfraspecificRank(parser.getInfraspecificRank()); s.setAuthorship(parser.getAuthorship()); s.setDrawerNumber(((DrawerNameReturner) parser).getDrawerNumber()); s.setCollection(((CollectionReturner) parser).getCollection()); s.setCreatingPath(ImageCaptureProperties.getPathBelowBase(fileToCheck)); s.setCreatingFilename(fileToCheck.getName()); if (parser.getIdentifiedBy() != null && parser.getIdentifiedBy().length() > 0) { s.setIdentifiedBy(parser.getIdentifiedBy()); } log.debug(s.getCollection()); // TODO: non-general workflows // ********* Special Cases ********** if (s.getWorkFlowStatus().equals(WorkFlowStatus.STAGE_0)) { // ***** Special case, images in ent-formicidae // get family set to Formicidae if in state OCR. if (path.contains("formicidae")) { s.setFamily("Formicidae"); } } s.setLocationInCollection(LocationInCollection.getDefaultLocation()); if (s.getFamily().equals("Formicidae")) { // ***** Special case, families in Formicidae are in Ant collection s.setLocationInCollection(LocationInCollection.GENERALANT); } // ********* End Special Cases ********** s.setCreatedBy(ImageCaptureApp.APP_NAME + " " + ImageCaptureApp.APP_VERSION); SpecimenLifeCycle sh = new SpecimenLifeCycle(); try { sh.persist(s); s.attachNewPart(); } catch (SpecimenExistsException e) { log.debug(e); JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), filename + " " + barcode + " \n" + e.getMessage(), "Specimen Exists, linking Image to existing record.", JOptionPane.ERROR_MESSAGE); List<Specimen> checkResult = sh.findByBarcode(barcode); if (checkResult.size() == 1) { s = checkResult.get(0); } } catch (SaveFailedException e) { // Couldn't save, but for some reason other than the // specimen record already existing. log.debug(e); try { List<Specimen> checkResult = sh.findByBarcode(barcode); if (checkResult.size() == 1) { s = checkResult.get(0); } // Drawer number with length limit (and specimen that fails to save at over this length makes // a good canary for labels that parse very badly. String badParse = ""; if (((DrawerNameReturner) parser).getDrawerNumber().length() > MetadataRetriever .getFieldLength(Specimen.class, "DrawerNumber")) { badParse = "Parsing problem. \nDrawer number is too long: " + s.getDrawerNumber() + "\n"; } JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), filename + " " + barcode + " \n" + badParse + e.getMessage(), "Badly parsed OCR", JOptionPane.ERROR_MESSAGE); } catch (Exception err) { log.error(e); log.error(err); // TODO: Add a general error handling/inform user class. // Cause of exception is not likely to be drawer number now that drawer number // length is enforced in Specimen.setDrawerNumber, but the text returned by the parser // might indicate very poor OCR as a cause. String badParse = ((DrawerNameReturner) parser).getDrawerNumber(); JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), filename + " " + barcode + "\n" + badParse + e.getMessage(), "Save Failed", JOptionPane.ERROR_MESSAGE); s = null; } } setPercentComplete(70); if (s != null) { tryMe.setSpecimen(s); } } tryMe.setRawBarcode(rawBarcode); if (isDrawerImage) { tryMe.setDrawerNumber(exifComment); } else { tryMe.setRawExifBarcode(exifComment); tryMe.setDrawerNumber(((DrawerNameReturner) parser).getDrawerNumber()); } tryMe.setRawOcr(rawOCR); tryMe.setTemplateId(defaultTemplate.getTemplateId()); tryMe.setPath(path); if (tryMe.getMd5sum() == null || tryMe.getMd5sum().length() == 0) { try { tryMe.setMd5sum(DigestUtils.md5Hex(new FileInputStream(fileToCheck))); } catch (FileNotFoundException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); } } try { imageCont.persist(tryMe); } catch (SaveFailedException e) { // TODO Auto-generated catch block log.error(e.getMessage()); e.printStackTrace(); } setPercentComplete(80); if (isSpecimenImage) { SpecimenControler controler = null; try { controler = new SpecimenControler(tryMe.getSpecimen()); controler.setTargetFrame(resultFrame); } catch (NoSuchRecordException e) { // TODO Auto-generated catch block e.printStackTrace(); } SpecimenDetailsViewPane sPane = new SpecimenDetailsViewPane(tryMe.getSpecimen(), controler); resultFrame.addWest((JPanel) sPane); if (!tryMe.getRawBarcode().equals(tryMe.getRawExifBarcode())) { if (Singleton.getSingletonInstance().getProperties().getProperties() .getProperty(ImageCaptureProperties.KEY_REDUNDANT_COMMENT_BARCODE) .equals("true")) { // If so configured, warn about missmatch sPane.setWarning( "Warning: Scanned Image has missmatch between barcode and comment."); } } } resultFrame.center(); } else { // found one or more matching image records. setPercentComplete(80); Singleton.getSingletonInstance().getMainFrame() .setStatusMessage("Loading existing image record."); ICImage existing = imageCont.findById(matches.get(0).getImageId()); System.out.println(existing.getRawBarcode()); existing.setRawBarcode(barcode); if (isDrawerImage) { existing.setDrawerNumber(exifComment); } else { existing.setRawExifBarcode(exifComment); } existing.setTemplateId(defaultTemplate.getTemplateId()); if (existing.getPath() == null || existing.getPath().equals("")) { existing.setPath(path); } if (existing.getDrawerNumber() == null || existing.getDrawerNumber().equals("")) { existing.setDrawerNumber(((DrawerNameReturner) parser).getDrawerNumber()); } try { imageCont.attachDirty(existing); } catch (SaveFailedException e) { // TODO Auto-generated catch block log.error(e.getMessage()); e.printStackTrace(); } if (isSpecimenImage) { SpecimenControler controler = null; try { controler = new SpecimenControler(existing.getSpecimen()); controler.setTargetFrame(resultFrame); System.out.println(existing.getSpecimen().getBarcode()); } catch (NullPointerException e1) { log.debug("Specimen barcode not set"); } catch (NoSuchRecordException e) { // Failure case log.error(e.getMessage(), e); JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), filename + " " + barcode + "\n" + "Existing Image record with no Specimen Record. " + e.getMessage(), "Save Failed.", JOptionPane.ERROR_MESSAGE); } SpecimenDetailsViewPane sPane = new SpecimenDetailsViewPane(existing.getSpecimen(), controler); resultFrame.addWest((JPanel) sPane); resultFrame.center(); resultFrame.setActiveTab(ImageDisplayFrame.TAB_LABELS); resultFrame.fitPinLabels(); if (!existing.getRawBarcode().equals(existing.getRawExifBarcode())) { if (Singleton.getSingletonInstance().getProperties().getProperties() .getProperty(ImageCaptureProperties.KEY_REDUNDANT_COMMENT_BARCODE) .equals("true")) { sPane.setWarning( "Warning: Scanned Image has missmatch between barcode and comment."); } } } setPercentComplete(90); } } } catch (UnreadableFileException e1) { log.error("Unable to read selected file." + e1.getMessage()); } catch (OCRReadException e) { log.error("Failed to OCR file." + e.getMessage()); } } else { System.out.println("No file selected from dialog."); } setPercentComplete(100); Singleton.getSingletonInstance().getMainFrame().setStatusMessage(""); SpecimenLifeCycle sls = new SpecimenLifeCycle(); Singleton.getSingletonInstance().getMainFrame().setCount(sls.findSpecimenCount()); Singleton.getSingletonInstance().getJobList().removeJob((RunnableJob) this); }
From source file:com.raddle.tools.MergeMain.java
private void initGUI() { try {//from w w w . j ava 2s. c o m { this.setBounds(0, 0, 1050, 600); getContentPane().setLayout(null); this.setTitle("\u5c5e\u6027\u6587\u4ef6\u6bd4\u8f83"); { sourceTxt = new JTextField(); getContentPane().add(sourceTxt); sourceTxt.setBounds(12, 12, 373, 22); } { sourceBtn = new JButton(); getContentPane().add(sourceBtn); sourceBtn.setText("\u6253\u5f00"); sourceBtn.setBounds(406, 12, 74, 22); sourceBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { JFileChooser fileChooser = new JFileChooser(); // fileChooser.addChoosableFileFilter( new FileNameExtensionFilter("", "properties")); File curFile = new File(sourceTxt.getText()); if (curFile.exists()) { fileChooser.setCurrentDirectory(curFile.getParentFile()); } int result = fileChooser.showOpenDialog(MergeMain.this); if (result == JFileChooser.APPROVE_OPTION) { File selected = fileChooser.getSelectedFile(); source = new PropertyHolder(selected, "utf-8"); sourceTxt.setText(selected.getAbsolutePath()); properties.setProperty("left.file", selected.getAbsolutePath()); savePropMergeFile(); compare(); } } }); } { targetTxt = new JTextField(); getContentPane().add(targetTxt); targetTxt.setBounds(496, 12, 419, 22); } { targetBtn = new JButton(); getContentPane().add(targetBtn); targetBtn.setText("\u6253\u5f00"); targetBtn.setBounds(935, 12, 81, 22); targetBtn.setSize(74, 22); targetBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { JFileChooser fileChooser = new JFileChooser(); // fileChooser.addChoosableFileFilter( new FileNameExtensionFilter("", "properties")); File curFile = new File(targetTxt.getText()); if (curFile.exists()) { fileChooser.setCurrentDirectory(curFile.getParentFile()); } int result = fileChooser.showOpenDialog(MergeMain.this); if (result == JFileChooser.APPROVE_OPTION) { File selected = fileChooser.getSelectedFile(); target = new PropertyHolder(selected, "utf-8"); targetTxt.setText(selected.getAbsolutePath()); properties.setProperty("right.file", selected.getAbsolutePath()); savePropMergeFile(); compare(); } } }); } { jScrollPane1 = new JScrollPane(); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(12, 127, 373, 413); { ListModel sourceListModel = new DefaultComboBoxModel(new String[] {}); sourceList = new JList(); jScrollPane1.setViewportView(sourceList); sourceList.setAutoscrolls(true); sourceList.setModel(sourceListModel); sourceList.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent evt) { if (evt.getKeyCode() == KeyEvent.VK_DELETE) { PropertyLine v = (PropertyLine) sourceList.getSelectedValue(); if (v != null) { int ret = JOptionPane.showConfirmDialog(MergeMain.this, "?" + v.getKey() + "?"); if (ret == JOptionPane.YES_OPTION) { v.setState(LineState.deleted); compare(); sourceList.setSelectedValue(v, true); } } } } }); sourceList.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { Object v = sourceList.getSelectedValue(); updatePropertyLine((PropertyLine) v); sourceList.setSelectedValue(v, true); } } }); sourceList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent evt) { if (sourceList.getSelectedValue() != null) { PropertyLine pl = (PropertyLine) sourceList.getSelectedValue(); if (target != null) { PropertyLine p = target.getLine(pl.getKey()); if (p != null) { TextDiffResult rt = TextdiffUtil.getDifferResult(p.toString(), pl.toString()); diffResultPane.setText("" + rt.getTargetHtml() + "<br/>?" + rt.getSrcHtml()); selectLine(targetList, p); return; } } TextDiffResult rt = TextdiffUtil.getDifferResult("", pl.toString()); diffResultPane.setText( "" + rt.getTargetHtml() + "<br/>?" + rt.getSrcHtml()); } } }); } } { jScrollPane2 = new JScrollPane(); getContentPane().add(jScrollPane2); jScrollPane2.setBounds(496, 127, 419, 413); { ListModel targetListModel = new DefaultComboBoxModel(new String[] {}); targetList = new JList(); jScrollPane2.setViewportView(targetList); targetList.setAutoscrolls(true); targetList.setModel(targetListModel); targetList.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent evt) { if (evt.getKeyCode() == KeyEvent.VK_DELETE) { PropertyLine v = (PropertyLine) targetList.getSelectedValue(); if (v != null) { int ret = JOptionPane.showConfirmDialog(MergeMain.this, "?" + v.getKey() + "?"); if (ret == JOptionPane.YES_OPTION) { v.setState(LineState.deleted); compare(); targetList.setSelectedValue(v, true); } } } } }); targetList.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { Object v = targetList.getSelectedValue(); updatePropertyLine((PropertyLine) v); targetList.setSelectedValue(v, true); } } }); targetList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent evt) { if (targetList.getSelectedValue() != null) { PropertyLine pl = (PropertyLine) targetList.getSelectedValue(); if (source != null) { PropertyLine s = source.getLine(pl.getKey()); if (s != null) { TextDiffResult rt = TextdiffUtil.getDifferResult(pl.toString(), s.toString()); diffResultPane.setText("" + rt.getTargetHtml() + "<br/>?" + rt.getSrcHtml()); selectLine(sourceList, s); return; } } TextDiffResult rt = TextdiffUtil.getDifferResult(pl.toString(), ""); diffResultPane.setText( "" + rt.getTargetHtml() + "<br/>?" + rt.getSrcHtml()); } } }); } } { sourceSaveBtn = new JButton(); getContentPane().add(sourceSaveBtn); sourceSaveBtn.setText("\u4fdd\u5b58"); sourceSaveBtn.setBounds(406, 45, 74, 22); sourceSaveBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { int result = JOptionPane.showConfirmDialog(MergeMain.this, "???\n" + source.getPropertyFile().getAbsolutePath()); if (result == JOptionPane.YES_OPTION) { source.saveFile(); JOptionPane.showMessageDialog(MergeMain.this, "??"); clearState(source); compare(); } } }); } { targetSaveBtn = new JButton(); getContentPane().add(targetSaveBtn); targetSaveBtn.setText("\u4fdd\u5b58"); targetSaveBtn.setBounds(935, 45, 81, 22); targetSaveBtn.setSize(74, 22); targetSaveBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { int result = JOptionPane.showConfirmDialog(MergeMain.this, "????\n" + target.getPropertyFile().getAbsolutePath()); if (result == JOptionPane.YES_OPTION) { target.saveFile(); JOptionPane.showMessageDialog(MergeMain.this, "??"); clearState(target); compare(); } } }); } { toTargetBtn = new JButton(); getContentPane().add(toTargetBtn); toTargetBtn.setText("->"); toTargetBtn.setBounds(406, 221, 74, 22); toTargetBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { Object[] oo = sourceList.getSelectedValues(); for (Object selected : oo) { PropertyLine s = (PropertyLine) selected; if (s != null && target != null) { PropertyLine t = target.getLine(s.getKey()); if (t == null) { PropertyLine n = s.clone(); n.setState(LineState.added); target.addPropertyLineAtSuitedPosition(n); } else if (!t.getValue().equals(s.getValue())) { t.setState(LineState.updated); t.setValue(s.getValue()); } else if (t.getState() == LineState.deleted) { if (t.getValue().equals(t.getOriginalValue())) { t.setState(LineState.original); } else { t.setState(LineState.updated); } } compare(); } } } }); } { toSourceBtn = new JButton(); getContentPane().add(toSourceBtn); toSourceBtn.setText("<-"); toSourceBtn.setBounds(406, 255, 74, 22); toSourceBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { Object[] oo = targetList.getSelectedValues(); for (Object selected : oo) { PropertyLine t = (PropertyLine) selected; if (t != null && source != null) { PropertyLine s = source.getLine(t.getKey()); if (s == null) { PropertyLine n = t.clone(); n.setState(LineState.added); source.addPropertyLineAtSuitedPosition(n); } else if (!s.getValue().equals(t.getValue())) { s.setState(LineState.updated); s.setValue(t.getValue()); } else if (s.getState() == LineState.deleted) { if (s.getValue().equals(s.getOriginalValue())) { s.setState(LineState.original); } else { s.setState(LineState.updated); } } compare(); } } } }); } { jScrollPane3 = new JScrollPane(); getContentPane().add(jScrollPane3); jScrollPane3.setBounds(12, 73, 903, 42); { diffResultPane = new JTextPane(); jScrollPane3.setViewportView(diffResultPane); diffResultPane.setBounds(12, 439, 903, 63); diffResultPane.setContentType("text/html"); diffResultPane.setPreferredSize(new java.awt.Dimension(901, 42)); } } { compareBtn = new JButton(); getContentPane().add(compareBtn); compareBtn.setText("\u6bd4\u8f83"); compareBtn.setBounds(406, 139, 74, 22); compareBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { compare(); } }); } { sourceReloadBtn = new JButton(); getContentPane().add(sourceReloadBtn); sourceReloadBtn.setText("\u91cd\u65b0\u8f7d\u5165"); sourceReloadBtn.setBounds(12, 40, 64, 29); sourceReloadBtn.setSize(90, 22); sourceReloadBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { if (sourceTxt.getText().length() > 0) { File curFile = new File(sourceTxt.getText().trim()); if (curFile.exists()) { source = new PropertyHolder(curFile, "utf-8"); sourceTxt.setText(curFile.getAbsolutePath()); properties.setProperty("left.file", curFile.getAbsolutePath()); savePropMergeFile(); compare(); } else { JOptionPane.showMessageDialog(MergeMain.this, "" + curFile.getAbsolutePath() + "?"); } } } }); } { targetReloadBtn = new JButton(); getContentPane().add(targetReloadBtn); targetReloadBtn.setText("\u91cd\u65b0\u8f7d\u5165"); targetReloadBtn.setBounds(839, 45, 90, 22); targetReloadBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { if (targetTxt.getText().length() > 0) { File curFile = new File(targetTxt.getText().trim()); if (curFile.exists()) { target = new PropertyHolder(curFile, "utf-8"); targetTxt.setText(curFile.getAbsolutePath()); properties.setProperty("right.file", curFile.getAbsolutePath()); savePropMergeFile(); compare(); } else { JOptionPane.showMessageDialog(MergeMain.this, "" + curFile.getAbsolutePath() + "?"); } } } }); } { helpBtn = new JButton(); getContentPane().add(helpBtn); helpBtn.setText("\u5e2e\u52a9"); helpBtn.setBounds(405, 338, 38, 29); helpBtn.setSize(74, 22); helpBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { StringBuilder sb = new StringBuilder(); sb.append("?").append("\n"); sb.append("del").append("\n"); sb.append("??").append("\n"); sb.append(": /.prop-merge/prop-merge.properties").append("\n"); JOptionPane.showMessageDialog(MergeMain.this, sb.toString()); } }); } { sourceEditBtn = new JButton(); getContentPane().add(sourceEditBtn); sourceEditBtn.setText("\u7f16\u8f91\u6587\u4ef6"); sourceEditBtn.setBounds(108, 40, 90, 22); sourceEditBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { if (sourceTxt.getText().length() > 0) { File curFile = new File(sourceTxt.getText()); editFile(curFile); } } }); } { targetEditBtn = new JButton(); getContentPane().add(targetEditBtn); targetEditBtn.setText("\u7f16\u8f91\u6587\u4ef6"); targetEditBtn.setBounds(743, 45, 90, 22); targetEditBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { if (targetTxt.getText().length() > 0) { File curFile = new File(targetTxt.getText()); editFile(curFile); } } }); } } pack(); } catch (Exception e) { e.printStackTrace(); } }
From source file:net.panthema.BispanningGame.GamePanel.java
public void writePdf() throws FileNotFoundException, DocumentException { // Query user for filename JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("Specify PDF file to save"); chooser.setCurrentDirectory(new File(".")); FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF Documents", "pdf"); chooser.setFileFilter(filter);//from w ww .j av a 2 s . co m if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return; File outfile = chooser.getSelectedFile(); if (!outfile.getAbsolutePath().endsWith(".pdf")) { outfile = new File(outfile.getAbsolutePath() + ".pdf"); } // Calculate page size rectangle Dimension size = mVV.getSize(); Rectangle rsize = new Rectangle(size.width, size.height); // Open the PDF file for writing - and create a Graphics2D object Document document = new Document(rsize); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outfile)); document.open(); PdfContentByte contentByte = writer.getDirectContent(); PdfGraphics2D graphics2d = new PdfGraphics2D(contentByte, size.width, size.height, new DefaultFontMapper()); // Create a container to hold the visualization Container container = new Container(); container.addNotify(); container.add(mVV); container.setVisible(true); container.paintComponents(graphics2d); // Dispose of the graphics and close the document graphics2d.dispose(); document.close(); // Put mVV back onto visible plane setLayout(new BorderLayout()); add(mVV, BorderLayout.CENTER); }
From source file:net.panthema.BispanningGame.GamePanel.java
public void writeGraphML() throws IOException { // Query user for filename JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("Specify GraphML file to save"); chooser.setCurrentDirectory(new File(".")); FileNameExtensionFilter filter = new FileNameExtensionFilter("GraphML File", "graphml"); chooser.setFileFilter(filter);/*from w w w .j av a2 s.co m*/ if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return; File outfile = chooser.getSelectedFile(); if (!outfile.getAbsolutePath().endsWith(".graphml")) { outfile = new File(outfile.getAbsolutePath() + ".graphml"); } // construct graphml writer GraphMLWriter<Integer, MyEdge> graphWriter = new GraphMLWriter<Integer, MyEdge>(); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outfile))); graphWriter.addVertexData("x", null, "0", new Transformer<Integer, String>() { public String transform(Integer v) { return Double.toString(mLayout.getX(v)); } }); graphWriter.addVertexData("y", null, "0", new Transformer<Integer, String>() { public String transform(Integer v) { return Double.toString(mLayout.getY(v)); } }); graphWriter.addEdgeData("color", null, "0", new Transformer<MyEdge, String>() { public String transform(MyEdge e) { return Integer.toString(e.color); } }); graphWriter.save(mGraph, out); }
From source file:ElectionGUI.java
private void saveElectionBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveElectionBtnActionPerformed JFileChooser fileChooser = new JFileChooser(); fileChooser.setApproveButtonText("Save"); fileChooser.setCurrentDirectory(folder); int result = fileChooser.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { folder = fileChooser.getCurrentDirectory(); File selectedFile = fileChooser.getSelectedFile(); Store2dElection store = new Store2dElection(this, selectedFile); store.writeToFile();//from w ww. j a v a 2 s . com systemTxt.append("-Election saved successfully." + eol); saved = true; } else if (result == JFileChooser.CANCEL_OPTION) { systemTxt.append("-Saving cancelled" + eol); } }
From source file:fll.scheduler.SchedulerUI.java
void saveScheduleDescription() { if (null == mScheduleDescriptionFile) { // prompt the user for a filename to save to final String startingDirectory = PREFS.get(DESCRIPTION_STARTING_DIRECTORY_PREF, null); final JFileChooser fileChooser = new JFileChooser(); final FileFilter filter = new BasicFileFilter("FLL Schedule Description (properties)", new String[] { "properties" }); fileChooser.setFileFilter(filter); if (null != startingDirectory) { fileChooser.setCurrentDirectory(new File(startingDirectory)); }/*from ww w. java2s . c o m*/ final int returnVal = fileChooser.showSaveDialog(SchedulerUI.this); if (returnVal == JFileChooser.APPROVE_OPTION) { final File currentDirectory = fileChooser.getCurrentDirectory(); PREFS.put(DESCRIPTION_STARTING_DIRECTORY_PREF, currentDirectory.getAbsolutePath()); mScheduleDescriptionFile = fileChooser.getSelectedFile(); mDescriptionFilename.setText(mScheduleDescriptionFile.getName()); } else { // user canceled return; } } try (final Writer writer = new OutputStreamWriter(new FileOutputStream(mScheduleDescriptionFile), Utilities.DEFAULT_CHARSET)) { final SolverParams params = mScheduleDescriptionEditor.getParams(); final List<String> errors = params.isValid(); if (!errors.isEmpty()) { final String formattedErrors = errors.stream().collect(Collectors.joining("\n")); JOptionPane.showMessageDialog(SchedulerUI.this, "There are errors that need to be corrected before the description can be saved: " + formattedErrors, "Error saving file", JOptionPane.ERROR_MESSAGE); } else { final Properties properties = new Properties(); params.save(properties); properties.store(writer, null); } } catch (final IOException e) { final Formatter errorFormatter = new Formatter(); errorFormatter.format("Error saving file: %s", e.getMessage()); LOGGER.error(errorFormatter, e); JOptionPane.showMessageDialog(SchedulerUI.this, errorFormatter, "Error saving file", JOptionPane.ERROR_MESSAGE); } }