List of usage examples for javax.swing JFileChooser setFileSelectionMode
@BeanProperty(preferred = true, enumerationValues = { "JFileChooser.FILES_ONLY", "JFileChooser.DIRECTORIES_ONLY", "JFileChooser.FILES_AND_DIRECTORIES" }, description = "Sets the types of files that the JFileChooser can choose.") public void setFileSelectionMode(int mode)
JFileChooser
to allow the user to just select files, just select directories, or select both files and directories. From source file:be.ugent.maf.cellmissy.gui.controller.analysis.doseresponse.generic.LoadGenericDRDataController.java
/** * Private methods// w w w.j a v a 2s. c o m */ //init view private void initDataLoadingPanel() { dataLoadingPanel = new DRDataLoadingPanel(); /** * Action Listeners. */ //Popup file selector and import and parse the file dataLoadingPanel.getChooseFileButton().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Open a JFile Chooser JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle( "Choose a tabular file (XLS, XLSX, CSV, TSV) for the import of the experiment"); // to select only appropriate files fileChooser.setFileFilter(new FileFilter() { @Override public boolean accept(File f) { if (f.isDirectory()) { return true; } int index = f.getName().lastIndexOf("."); String extension = f.getName().substring(index + 1); return extension.equals("xls") || extension.equals("xlsx") || extension.equals("csv") || extension.equals("tsv"); } @Override public String getDescription() { return (".xls, .xlsx, .csv and .tsv files"); } }); fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); fileChooser.setAcceptAllFileFilterUsed(false); // in response to the button click, show open dialog int returnVal = fileChooser.showOpenDialog(dataLoadingPanel); if (returnVal == JFileChooser.APPROVE_OPTION) { File chosenFile = fileChooser.getSelectedFile(); // // create and execute a new swing worker with the selected file for the import // ImportExperimentSwingWorker importExperimentSwingWorker = new ImportExperimentSwingWorker(chosenFile); // importExperimentSwingWorker.execute(); parseDRFile(chosenFile); if (doseResponseController.getImportedDRDataHolder().getDoseResponseData() != null) { dataLoadingPanel.getFileLabel().setText(chosenFile.getAbsolutePath()); doseResponseController.getGenericDRParentPanel().getNextButton().setEnabled(true); } } else { JOptionPane.showMessageDialog(dataLoadingPanel, "Command cancelled by user", "", JOptionPane.INFORMATION_MESSAGE); } } }); dataLoadingPanel.getLogTransformCheckBox().addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { doseResponseController.setLogTransform(true); } else { doseResponseController.setLogTransform(false); } } }); }
From source file:com.floreantpos.ui.model.PizzaItemForm.java
private void doSelectImageFile() { JFileChooser fileChooser = new JFileChooser(); fileChooser.setMultiSelectionEnabled(false); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int option = fileChooser.showOpenDialog(POSUtil.getBackOfficeWindow()); if (option == JFileChooser.APPROVE_OPTION) { File imageFile = fileChooser.getSelectedFile(); try {//from w ww. j a v a2s. com byte[] itemImage = FileUtils.readFileToByteArray(imageFile); int imageSize = itemImage.length / 1024; if (imageSize > 20) { POSMessageDialog.showMessage(Messages.getString("MenuItemForm.0")); //$NON-NLS-1$ itemImage = null; return; } ImageIcon imageIcon = new ImageIcon( new ImageIcon(itemImage).getImage().getScaledInstance(80, 80, Image.SCALE_SMOOTH)); lblImagePreview.setIcon(imageIcon); MenuItem menuItem = (MenuItem) getBean(); menuItem.setImageData(itemImage); } catch (IOException e) { PosLog.error(getClass(), e); } } }
From source file:de.codesourcery.eve.skills.ui.components.impl.MarketPriceEditorComponent.java
private void importMarketLogs() { File inputDir = null;/*from w ww . j a v a 2s. c om*/ if (appConfigProvider.getAppConfig().hasLastMarketLogImportDirectory()) { inputDir = appConfigProvider.getAppConfig().getLastMarketLogImportDirectory(); if (!inputDir.exists() || !inputDir.isDirectory()) { inputDir = null; } } final JFileChooser chooser = inputDir != null ? new JFileChooser(inputDir) : new JFileChooser(); chooser.setFileHidingEnabled(false); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setMultiSelectionEnabled(true); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File[] files = chooser.getSelectedFiles(); if (!ArrayUtils.isEmpty(files)) { appConfigProvider.getAppConfig().setLastMarketLogImportDirectory(files[0].getParentFile()); try { appConfigProvider.save(); } catch (IOException e) { log.error("importMarketLogs(): Failed to save configuration", e); } importMarketLogs(files); } } }
From source file:gdt.jgui.entity.folder.JFolderPanel.java
/** * Get the context menu.//from w ww. ja va 2s. c o m * @return the context menu. */ @Override public JMenu getContextMenu() { menu = super.getContextMenu(); mia = null; int cnt = menu.getItemCount(); if (cnt > 0) { mia = new JMenuItem[cnt]; for (int i = 0; i < cnt; i++) mia[i] = menu.getItem(i); } menu.addMenuListener(new MenuListener() { @Override public void menuSelected(MenuEvent e) { //System.out.println("EntitiesPanel:getConextMenu:menu selected"); menu.removeAll(); if (mia != null) { for (JMenuItem mi : mia) menu.add(mi); menu.addSeparator(); } JMenuItem refreshItem = new JMenuItem("Refresh"); refreshItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JConsoleHandler.execute(console, locator$); } }); menu.add(refreshItem); JMenuItem openItem = new JMenuItem("Open folder"); openItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { File folder = new File(entihome$ + "/" + entityKey$); if (!folder.exists()) folder.mkdir(); Desktop.getDesktop().open(folder); } catch (Exception ee) { LOGGER.severe(ee.toString()); } } }); menu.add(openItem); JMenuItem importItem = new JMenuItem("Import"); importItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { File home = new File(System.getProperty("user.home")); Desktop.getDesktop().open(home); } catch (Exception ee) { LOGGER.severe(ee.toString()); } } }); menu.add(importItem); JMenuItem newItem = new JMenuItem("New text"); newItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { JTextEditor textEditor = new JTextEditor(); String teLocator$ = textEditor.getLocator(); teLocator$ = Locator.append(teLocator$, Entigrator.ENTIHOME, entihome$); String text$ = "New" + Identity.key().substring(0, 4) + ".txt"; teLocator$ = Locator.append(teLocator$, JTextEditor.TEXT, text$); JFolderPanel fp = new JFolderPanel(); String fpLocator$ = fp.getLocator(); fpLocator$ = Locator.append(fpLocator$, Entigrator.ENTIHOME, entihome$); fpLocator$ = Locator.append(fpLocator$, EntityHandler.ENTITY_KEY, entityKey$); fpLocator$ = Locator.append(fpLocator$, BaseHandler.HANDLER_METHOD, "response"); fpLocator$ = Locator.append(fpLocator$, JRequester.REQUESTER_ACTION, ACTION_CREATE_FILE); String requesterResponseLocator$ = Locator.compressText(fpLocator$); teLocator$ = Locator.append(teLocator$, JRequester.REQUESTER_RESPONSE_LOCATOR, requesterResponseLocator$); JConsoleHandler.execute(console, teLocator$); } catch (Exception ee) { LOGGER.severe(ee.toString()); } } }); menu.add(newItem); //menu.addSeparator(); if (hasToInsert()) { menu.addSeparator(); JMenuItem insertItem = new JMenuItem("Insert"); insertItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable clipboardContents = systemClipboard.getContents(null); if (clipboardContents == null) return; Object transferData = clipboardContents .getTransferData(DataFlavor.javaFileListFlavor); List<File> files = (List<File>) transferData; for (int i = 0; i < files.size(); i++) { File file = (File) files.get(i); if (file.exists() && file.isFile()) { System.out.println("FolderPanel:insert:in=" + file.getPath()); File dir = new File(entihome$ + "/" + entityKey$); if (!dir.exists()) dir.mkdir(); File out = new File(entihome$ + "/" + entityKey$ + "/" + file.getName()); if (!out.exists()) out.createNewFile(); System.out.println("FolderPanel:insert:out=" + out.getPath()); FileExpert.copyFile(file, out); JConsoleHandler.execute(console, getLocator()); } // System.out.println("FolderPanel:import:file="+file.getPath()); } } catch (Exception ee) { LOGGER.severe(ee.toString()); } } }); menu.add(insertItem); } if (hasToPaste()) { menu.addSeparator(); JMenuItem pasteItem = new JMenuItem("Paste"); pasteItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String[] sa = console.clipboard.getContent(); Properties locator; String file$; File file; File target; String dir$ = entihome$ + "/" + entityKey$; File dir = new File(dir$); if (!dir.exists()) dir.mkdir(); for (String aSa : sa) { try { locator = Locator.toProperties(aSa); if (LOCATOR_TYPE_FILE.equals(locator.getProperty(Locator.LOCATOR_TYPE))) { file$ = locator.getProperty(FILE_PATH); file = new File(file$); target = new File(dir$ + "/" + file.getName()); if (!target.exists()) target.createNewFile(); FileExpert.copyFile(file, target); } } catch (Exception ee) { LOGGER.info(ee.toString()); } } JConsoleHandler.execute(console, locator$); } }); menu.add(pasteItem); } if (hasSelectedItems()) { menu.addSeparator(); JMenuItem deleteItem = new JMenuItem("Delete"); deleteItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int response = JOptionPane.showConfirmDialog(console.getContentPanel(), "Delete ?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (response == JOptionPane.YES_OPTION) { String[] sa = JFolderPanel.this.listSelectedItems(); if (sa == null) return; Properties locator; String file$; File file; for (String aSa : sa) { locator = Locator.toProperties(aSa); file$ = locator.getProperty(FILE_PATH); file = new File(file$); try { if (file.isDirectory()) FileExpert.clear(file$); file.delete(); } catch (Exception ee) { LOGGER.info(ee.toString()); } } } JConsoleHandler.execute(console, locator$); } }); menu.add(deleteItem); JMenuItem copyItem = new JMenuItem("Copy"); copyItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String[] sa = JFolderPanel.this.listSelectedItems(); console.clipboard.clear(); if (sa != null) for (String aSa : sa) console.clipboard.putString(aSa); } }); menu.add(copyItem); JMenuItem exportItem = new JMenuItem("Export"); exportItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { String[] sa = JFolderPanel.this.listSelectedItems(); Properties locator; String file$; File file; ArrayList<File> fileList = new ArrayList<File>(); for (String aSa : sa) { try { locator = Locator.toProperties(aSa); file$ = locator.getProperty(FILE_PATH); file = new File(file$); fileList.add(file); } catch (Exception ee) { LOGGER.severe(ee.toString()); } } File[] fa = fileList.toArray(new File[0]); if (fa.length < 1) return; // System.out.println("Folderpanel:finish:list="+fa.length); JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new java.io.File(System.getProperty("user.home"))); chooser.setDialogTitle("Export files"); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.setAcceptAllFileFilterUsed(false); if (chooser.showSaveDialog(JFolderPanel.this) == JFileChooser.APPROVE_OPTION) { String dir$ = chooser.getSelectedFile().getPath(); File target; for (File f : fa) { target = new File(dir$ + "/" + f.getName()); if (!target.exists()) target.createNewFile(); FileExpert.copyFile(f, target); } } else { Logger.getLogger(JMainConsole.class.getName()).info(" no selection"); } // System.out.println("Folderpanel:finish:list="+fileList.size()); } catch (Exception eee) { LOGGER.severe(eee.toString()); } } }); menu.add(exportItem); } } @Override public void menuDeselected(MenuEvent e) { } @Override public void menuCanceled(MenuEvent e) { } }); return menu; }
From source file:ctPrincipal.Principal.java
private File openImagem(String Dir, boolean lista) { JFileChooser fileChooser = new JFileChooser(); BufferedImage buff = null;/* w w w. j av a 2s. c om*/ String caminho = null; try { caminho = new File(".").getCanonicalPath() + Dir; } catch (IOException ex) { Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex); } fileChooser.setCurrentDirectory(new File(caminho)); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "gif", "bmp")); fileChooser.setAcceptAllFileFilterUsed(true); fileChooser.setMultiSelectionEnabled(true); int result = fileChooser.showOpenDialog(getComponent(0)); if (result == JFileChooser.APPROVE_OPTION) { if (lista) { File[] selectedFile = fileChooser.getSelectedFiles(); arquivos = new String[selectedFile.length]; for (int i = 0; i < selectedFile.length; i++) { selectedFile[i].setReadable(Boolean.TRUE); arquivos[i] = selectedFile[i].getAbsolutePath(); } jLTotal.setText("Total de Imagens : " + arquivos.length); } else { File selectedFile = fileChooser.getSelectedFile(); return selectedFile; } } return null; }
From source file:configuration.Util.java
public static String[] simpleSearchBox(String type, boolean multi, boolean hide) { JFrame f = createSearchFrame(); JFileChooser jf; jf = new JFileChooser(config.getExplorerPath()); if (type.contains("d") || type.contains("D")) jf.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); else if (type.contains("f") || type.contains("F")) jf.setFileSelectionMode(JFileChooser.FILES_ONLY); else/* w w w . j a v a2s. co m*/ jf.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); jf.setAcceptAllFileFilterUsed(false); jf.setMultiSelectionEnabled(multi); jf.setFileHidingEnabled(hide); int result = jf.showOpenDialog(f); f.dispose(); if (result == JFileChooser.APPROVE_OPTION) { if (multi) { //--Save new filepath and files File[] files = jf.getSelectedFiles(); String[] path = new String[files.length]; for (int i = 0; i < files.length; i++) { path[i] = getCanonicalPath(files[i].getPath()); } return path; } else { File file = jf.getSelectedFile(); String[] path = new String[1]; path[0] = getCanonicalPath(file.getPath()); return path; } } String[] empty = new String[0]; return empty; }
From source file:edu.ku.brc.specify.tasks.subpane.wb.ImageFrame.java
protected File[] askUserForImageFiles() { ImageFilter imageFilter = new ImageFilter(); JFileChooser fileChooser = new JFileChooser( WorkbenchTask.getDefaultDirPath(WorkbenchTask.IMAGES_FILE_PATH)); fileChooser.setFileFilter(imageFilter); fileChooser.setDialogTitle(getResourceString("WB_CHOOSE_IMAGES")); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.setMultiSelectionEnabled(true); int userAction = fileChooser.showOpenDialog(this); AppPreferences localPrefs = AppPreferences.getLocalPrefs(); // remember the directory the user was last in localPrefs.put(WorkbenchTask.IMAGES_FILE_PATH, fileChooser.getCurrentDirectory().getAbsolutePath()); if (userAction == JFileChooser.APPROVE_OPTION) { return fileChooser.getSelectedFiles(); }/*from www .jav a2 s . co m*/ // if for any reason we got to this point... return null; }
From source file:edu.ku.brc.specify.tasks.subpane.wb.ImageFrame.java
protected File askUserForImageFile() { ImageFilter imageFilter = new ImageFilter(); JFileChooser fileChooser = new JFileChooser( WorkbenchTask.getDefaultDirPath(WorkbenchTask.IMAGES_FILE_PATH)); fileChooser.setFileFilter(imageFilter); fileChooser.setDialogTitle(getResourceString("WB_CHOOSE_IMAGE")); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int userAction = fileChooser.showOpenDialog(this); AppPreferences localPrefs = AppPreferences.getLocalPrefs(); // remember the directory the user was last in localPrefs.put(WorkbenchTask.IMAGES_FILE_PATH, fileChooser.getCurrentDirectory().getAbsolutePath()); if (userAction == JFileChooser.APPROVE_OPTION) { String fullPath = fileChooser.getSelectedFile().getAbsolutePath(); if (imageFilter.isImageFile(fullPath)) { return fileChooser.getSelectedFile(); }// ww w.j a va 2 s. c o m } // if for any reason (user cancelled) we got to this point... return null; }
From source file:forge.gui.ImportDialog.java
@SuppressWarnings("serial") public ImportDialog(final String forcedSrcDir, final Runnable onDialogClose) { this.forcedSrcDir = forcedSrcDir; _topPanel = new FPanel(new MigLayout("insets dialog, gap 0, center, wrap, fill")); _topPanel.setOpaque(false);//from www . ja v a 2s . c om _topPanel.setBackgroundTexture(FSkin.getIcon(FSkinProp.BG_TEXTURE)); isMigration = !StringUtils.isEmpty(forcedSrcDir); // header _topPanel.add(new FLabel.Builder().text((isMigration ? "Migrate" : "Import") + " profile data").fontSize(15) .build(), "center"); // add some help text if this is for the initial data migration if (isMigration) { final FPanel blurbPanel = new FPanel(new MigLayout("insets panel, gap 10, fill")); blurbPanel.setOpaque(false); final JPanel blurbPanelInterior = new JPanel( new MigLayout("insets dialog, gap 10, center, wrap, fill")); blurbPanelInterior.setOpaque(false); blurbPanelInterior.add(new FLabel.Builder().text("<html><b>What's this?</b></html>").build(), "growx, w 50:50:"); blurbPanelInterior.add(new FLabel.Builder() .text("<html>Over the last several years, people have had to jump through a lot of hoops to" + " update to the most recent version. We hope to reduce this workload to a point where a new" + " user will find that it is fairly painless to update. In order to make this happen, Forge" + " has changed where it stores your data so that it is outside of the program installation directory." + " This way, when you upgrade, you will no longer need to import your data every time to get things" + " working. There are other benefits to having user data separate from program data, too, and it" + " lays the groundwork for some cool new features.</html>") .build(), "growx, w 50:50:"); blurbPanelInterior.add( new FLabel.Builder().text("<html><b>So where's my data going?</b></html>").build(), "growx, w 50:50:"); blurbPanelInterior.add(new FLabel.Builder().text( "<html>Forge will now store your data in the same place as other applications on your system." + " Specifically, your personal data, like decks, quest progress, and program preferences will be" + " stored in <b>" + ForgeConstants.USER_DIR + "</b> and all downloaded content, such as card pictures," + " skins, and quest world prices will be under <b>" + ForgeConstants.CACHE_DIR + "</b>. If, for whatever" + " reason, you need to set different paths, cancel out of this dialog, exit Forge, and find the <b>" + ForgeConstants.PROFILE_TEMPLATE_FILE + "</b> file in the program installation directory. Copy or rename" + " it to <b>" + ForgeConstants.PROFILE_FILE + "</b> and edit the paths inside it. Then restart Forge and use" + " this dialog to move your data to the paths that you set. Keep in mind that if you install a future" + " version of Forge into a different directory, you'll need to copy this file over so Forge will know" + " where to find your data.</html>") .build(), "growx, w 50:50:"); blurbPanelInterior.add(new FLabel.Builder().text( "<html><b>Remember, your data won't be available until you complete this step!</b></html>") .build(), "growx, w 50:50:"); final FScrollPane blurbScroller = new FScrollPane(blurbPanelInterior, true, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); blurbPanel.add(blurbScroller, "hmin 150, growy, growx, center, gap 0 0 5 5"); _topPanel.add(blurbPanel, "gap 10 10 20 0, growy, growx, w 50:50:"); } // import source widgets final JPanel importSourcePanel = new JPanel(new MigLayout("insets 0, gap 10")); importSourcePanel.setOpaque(false); importSourcePanel.add(new FLabel.Builder().text("Import from:").build()); _txfSrc = new FTextField.Builder().readonly().build(); importSourcePanel.add(_txfSrc, "pushx, growx"); _btnChooseDir = new FLabel.ButtonBuilder().text("Choose directory...").enabled(!isMigration).build(); final JFileChooser _fileChooser = new JFileChooser(); _fileChooser.setMultiSelectionEnabled(false); _fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); _btnChooseDir.setCommand(new UiCommand() { @Override public void run() { // bring up a file open dialog and, if the OK button is selected, apply the filename // to the import source text field if (JFileChooser.APPROVE_OPTION == _fileChooser.showOpenDialog(JOptionPane.getRootFrame())) { final File f = _fileChooser.getSelectedFile(); if (!f.canRead()) { FOptionPane.showErrorDialog("Cannot access selected directory (Permission denied)."); } else { _txfSrc.setText(f.getAbsolutePath()); } } } }); importSourcePanel.add(_btnChooseDir, "h pref+8!, w pref+12!"); // add change handler to the import source text field that starts up a // new analyzer. it also interacts with the current active analyzer, // if any, to make sure it cancels out before the new one is initiated _txfSrc.getDocument().addDocumentListener(new DocumentListener() { boolean _analyzerActive; // access synchronized on _onAnalyzerDone String prevText; private final Runnable _onAnalyzerDone = new Runnable() { @Override public synchronized void run() { _analyzerActive = false; notify(); } }; @Override public void removeUpdate(final DocumentEvent e) { } @Override public void changedUpdate(final DocumentEvent e) { } @Override public void insertUpdate(final DocumentEvent e) { // text field is read-only, so the only time this will get updated // is when _btnChooseDir does it final String text = _txfSrc.getText(); if (text.equals(prevText)) { // only restart the analyzer if the directory has changed return; } prevText = text; // cancel any active analyzer _cancel = true; if (!text.isEmpty()) { // ensure we don't get two instances of this function running at the same time _btnChooseDir.setEnabled(false); // re-disable the start button. it will be enabled if the previous analyzer has // already successfully finished _btnStart.setEnabled(false); // we have to wait in a background thread since we can't block in the GUI thread final SwingWorker<Void, Void> analyzerStarter = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { // wait for active analyzer (if any) to quit synchronized (_onAnalyzerDone) { while (_analyzerActive) { _onAnalyzerDone.wait(); } } return null; } // executes in gui event loop thread @Override protected void done() { _cancel = false; synchronized (_onAnalyzerDone) { // this will populate the panel with data selection widgets final _AnalyzerUpdater analyzer = new _AnalyzerUpdater(text, _onAnalyzerDone, isMigration); analyzer.run(); _analyzerActive = true; } if (!isMigration) { // only enable the directory choosing button if this is not a migration dialog // since in that case we're permanently locked to the starting directory _btnChooseDir.setEnabled(true); } } }; analyzerStarter.execute(); } } }); _topPanel.add(importSourcePanel, "gaptop 20, pushx, growx"); // prepare import selection panel (will be cleared and filled in later by an analyzer) _selectionPanel = new JPanel(); _selectionPanel.setOpaque(false); _topPanel.add(_selectionPanel, "growx, growy, gaptop 10"); // action button widgets final Runnable cleanup = new Runnable() { @Override public void run() { SOverlayUtils.hideOverlay(); } }; _btnStart = new FButton("Start import"); _btnStart.setEnabled(false); _btnCancel = new FButton("Cancel"); _btnCancel.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { _cancel = true; cleanup.run(); if (null != onDialogClose) { onDialogClose.run(); } } }); final JPanel southPanel = new JPanel(new MigLayout("ax center")); southPanel.setOpaque(false); southPanel.add(_btnStart, "center, w pref+144!, h pref+12!"); southPanel.add(_btnCancel, "center, w pref+144!, h pref+12!, gap 72"); _topPanel.add(southPanel, "growx"); }
From source file:edu.harvard.mcz.imagecapture.jobs.JobAllImageFilesScan.java
@Override public void start() { startTime = new Date(); Singleton.getSingletonInstance().getJobList().addJob((RunnableJob) this); runStatus = RunStatus.STATUS_RUNNING; File imagebase = null; // place to start the scan from, imagebase directory for SCAN_ALL startPoint = null;/* www. j a va2s . co m*/ // If it isn't null, retrieve the image base directory from properties, and test for read access. if (Singleton.getSingletonInstance().getProperties().getProperties() .getProperty(ImageCaptureProperties.KEY_IMAGEBASE) == null) { JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), "Can't start scan. Don't know where images are stored. Set imagbase property.", "Can't Scan.", JOptionPane.ERROR_MESSAGE); } else { imagebase = new File(Singleton.getSingletonInstance().getProperties().getProperties() .getProperty(ImageCaptureProperties.KEY_IMAGEBASE)); if (imagebase != null) { if (imagebase.canRead()) { startPoint = imagebase; } else { // If it can't be read, null out imagebase imagebase = null; } } if (scan == SCAN_SPECIFIC && startPointSpecific != null && startPointSpecific.canRead()) { // A scan start point has been provided, don't launch a dialog. startPoint = startPointSpecific; } if (imagebase == null || scan == SCAN_SELECT) { // launch a file chooser dialog to select the directory to scan final JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (scan == SCAN_SELECT && startPointSpecific != null && startPointSpecific.canRead()) { fileChooser.setCurrentDirectory(startPointSpecific); } else { if (Singleton.getSingletonInstance().getProperties().getProperties() .getProperty(ImageCaptureProperties.KEY_LASTPATH) != null) { fileChooser.setCurrentDirectory(new File(Singleton.getSingletonInstance().getProperties() .getProperties().getProperty(ImageCaptureProperties.KEY_LASTPATH))); } } int returnValue = fileChooser.showOpenDialog(Singleton.getSingletonInstance().getMainFrame()); if (returnValue == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); log.debug("Selected base directory: " + file.getName() + "."); startPoint = file; } else { //TODO: handle error condition log.error("Directory selection cancelled by user."); } //TODO: Filechooser to pick path, then save (if SCAN_ALL) imagebase property. //Perhaps. Might be undesirable behavior. //Probably better to warn that imagebase is null; } // TODO: Check that startPoint is or is within imagebase. // Check that fileToCheck is within imagebase. if (!ImageCaptureProperties.isInPathBelowBase(startPoint)) { String base = Singleton.getSingletonInstance().getProperties().getProperties() .getProperty(ImageCaptureProperties.KEY_IMAGEBASE); log.error("Tried to scan directory (" + startPoint.getPath() + ") outside of base image directory (" + base + ")"); String message = "Can't scan and database files outside of base image directory (" + base + ")"; JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), message, "Can't Scan outside image base directory.", JOptionPane.YES_NO_OPTION); } else { // run in separate thread and allow cancellation and status reporting // walk through directory tree if (!startPoint.canRead()) { JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), "Can't start scan. Unable to read selected directory: " + startPoint.getPath(), "Can't Scan.", JOptionPane.YES_NO_OPTION); } else { Singleton.getSingletonInstance().getMainFrame() .setStatusMessage("Scanning " + startPoint.getPath()); Counter counter = new Counter(); // count files to scan countFiles(startPoint, counter); setPercentComplete(0); Singleton.getSingletonInstance().getMainFrame().notifyListener(runStatus, this); counter.incrementDirectories(); // scan if (runStatus != RunStatus.STATUS_TERMINATED) { checkFiles(startPoint, counter); } // report String report = "Scanned " + counter.getDirectories() + " directories.\n"; report += "Created thumbnails in " + thumbnailCounter + " directories"; if (thumbnailCounter == 0) { report += " (May still be in progress)"; } report += ".\n"; if (startPointSpecific == null) { report += "Starting with the base image directory (Preprocess All).\n"; } else { report += "Starting with " + startPoint.getName() + " (" + startPoint.getPath() + ")\n"; report += "First file: " + firstFile + " Last File: " + lastFile + "\n"; } report += "Scanned " + counter.getFilesSeen() + " files.\n"; report += "Created " + counter.getFilesDatabased() + " new image records.\n"; if (counter.getFilesUpdated() > 0) { report += "Updated " + counter.getFilesUpdated() + " image records.\n"; } report += "Created " + counter.getSpecimens() + " new specimen records.\n"; if (counter.getSpecimensUpdated() > 0) { report += "Updated " + counter.getSpecimensUpdated() + " specimen records.\n"; } report += "Found " + counter.getFilesFailed() + " files with problems.\n"; //report += counter.getErrors(); Singleton.getSingletonInstance().getMainFrame().setStatusMessage("Preprocess scan complete"); setPercentComplete(100); Singleton.getSingletonInstance().getMainFrame().notifyListener(runStatus, this); RunnableJobReportDialog errorReportDialog = new RunnableJobReportDialog( Singleton.getSingletonInstance().getMainFrame(), report, counter.getErrors(), "Preprocess Results"); errorReportDialog.setVisible(true); //JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), report, "Preprocess complete", JOptionPane.ERROR_MESSAGE); } // can read directory } SpecimenLifeCycle sls = new SpecimenLifeCycle(); Singleton.getSingletonInstance().getMainFrame().setCount(sls.findSpecimenCount()); } // Imagebase isn't null done(); }