List of usage examples for javax.swing JOptionPane WARNING_MESSAGE
int WARNING_MESSAGE
To view the source code for javax.swing JOptionPane WARNING_MESSAGE.
Click Source Link
From source file:io.github.tavernaextras.biocatalogue.integration.config.BioCataloguePluginConfigurationPanel.java
/** * Saves recent changes to the configuration parameter map. * Some input validation is performed as well. *///from w w w . j av a 2s . c o m private void applyChanges() { // --- BioCatalogue BASE URL --- String candidateBaseURL = tfBioCatalogueAPIBaseURL.getText(); if (candidateBaseURL.length() == 0) { JOptionPane.showMessageDialog(this, "Service Catalogue base URL must not be blank", "Service Catalogue Configuration", JOptionPane.WARNING_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } else { try { new URL(candidateBaseURL); } catch (MalformedURLException e) { JOptionPane.showMessageDialog(this, "Currently set Service Catalogue instance URL is not valid\n." + "Please check the URL and try again.", "Service Catalogue Configuration", JOptionPane.WARNING_MESSAGE); tfBioCatalogueAPIBaseURL.selectAll(); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } // check if the base URL has changed from the last saved state if (!candidateBaseURL.equals( configuration.getProperty(BioCataloguePluginConfiguration.SERVICE_CATALOGUE_BASE_URL))) { // Perform various checks on the new URL // Do a GET with "Accept" header set to "application/xml" // We are expecting a 200 OK and an XML doc in return that // contains the BioCataogue version number element. DefaultHttpClient httpClient = new DefaultHttpClient(); // Set the proxy settings, if any if (System.getProperty(PROXY_HOST) != null && !System.getProperty(PROXY_HOST).equals("")) { // Instruct HttpClient to use the standard // JRE proxy selector to obtain proxy information ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); // Do we need to authenticate the user to the proxy? if (System.getProperty(PROXY_USERNAME) != null && !System.getProperty(PROXY_USERNAME).equals("")) { // Add the proxy username and password to the list of credentials httpClient.getCredentialsProvider().setCredentials( new AuthScope(System.getProperty(PROXY_HOST), Integer.parseInt(System.getProperty(PROXY_PORT))), new UsernamePasswordCredentials(System.getProperty(PROXY_USERNAME), System.getProperty(PROXY_PASSWORD))); } } HttpGet httpGet = new HttpGet(candidateBaseURL); httpGet.setHeader("Accept", APPLICATION_XML_MIME_TYPE); // Execute the request HttpContext localContext = new BasicHttpContext(); HttpResponse httpResponse; try { httpResponse = httpClient.execute(httpGet, localContext); } catch (Exception ex1) { logger.error( "Service Catalogue preferences configuration: Failed to do " + httpGet.getRequestLine(), ex1); // Warn the user JOptionPane.showMessageDialog(this, "Failed to connect to the URL of the Service Catalogue instance.\n" + "Please check the URL and try again.", "Service Catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); // Release resource httpClient.getConnectionManager().shutdown(); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } if (httpResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { // HTTP/1.1 200 OK HttpEntity httpEntity = httpResponse.getEntity(); String contentType = httpEntity.getContentType().getValue().toLowerCase().trim(); logger.info( "Service Catalogue preferences configuration: Got 200 OK when testing the Service Catalogue instance by doing " + httpResponse.getStatusLine() + ". Content type of response " + contentType); if (contentType.startsWith(APPLICATION_XML_MIME_TYPE)) { String value = null; Document doc = null; try { value = readResponseBodyAsString(httpEntity).trim(); // Try to read this string into an XML document SAXBuilder builder = new SAXBuilder(); byte[] bytes = value.getBytes("UTF-8"); doc = builder.build(new ByteArrayInputStream(bytes)); } catch (Exception ex2) { logger.error( "Service Catalogue preferences configuration: Failed to build an XML document from the response.", ex2); // Warn the user JOptionPane.showMessageDialog(this, "Failed to get the expected response body when testing the Service Catalogue instance.\n" + "The URL is probably wrong. Please check it and try again.", "Service Catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } finally { // Release resource httpClient.getConnectionManager().shutdown(); } // Get the version element from the XML document Attribute apiVersionAttribute = doc.getRootElement().getAttribute(API_VERSION); if (apiVersionAttribute != null) { String apiVersion = apiVersionAttribute.getValue(); String versions[] = apiVersion.split("[.]"); String majorVersion = versions[0]; String minorVersion = versions[1]; try { //String patchVersion = versions[2]; // we are not comparing the patch versions String supportedMajorVersion = MIN_SUPPORTED_BIOCATALOGUE_API_VERSION[0]; String supportedMinorVersion = MIN_SUPPORTED_BIOCATALOGUE_API_VERSION[1]; Integer iSupportedMajorVersion = Integer.parseInt(supportedMajorVersion); Integer iMajorVersion = Integer.parseInt(majorVersion); Integer iSupportedMinorVersion = Integer.parseInt(supportedMinorVersion); Integer iMinorVersion = Integer.parseInt(minorVersion); if (!(iSupportedMajorVersion == iMajorVersion && iSupportedMinorVersion <= iMinorVersion)) { // Warn the user JOptionPane.showMessageDialog(this, "The version of the Service Catalogue instance you are trying to connect to is not supported.\n" + "Please change the URL and try again.", "Service Catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } } catch (Exception e) { logger.error(e); } } // if null - we'll try to do our best to connect to BioCatalogue anyway } else { logger.error( "Service Catalogue preferences configuration: Failed to get the expected response content type when testing the Service Catalogue instance. " + httpGet.getRequestLine() + " returned content type '" + contentType + "'; expected response content type is 'application/xml'."); // Warn the user JOptionPane.showMessageDialog(this, "Failed to get the expected response content type when testing the Service Catalogue instance.\n" + "The URL is probably wrong. Please check it and try again.", "Service Catalogue Plugin", JOptionPane.INFORMATION_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } } else { logger.error( "Service Catalogue preferences configuration: Failed to get the expected response status code when testing the Service Catalogue instance. " + httpGet.getRequestLine() + " returned the status code " + httpResponse.getStatusLine().getStatusCode() + "; expected status code is 200 OK."); // Warn the user JOptionPane.showMessageDialog(this, "Failed to get the expected response status code when testing the Service Catalogue instance.\n" + "The URL is probably wrong. Please check it and try again.", "Service Catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } // Warn the user of the changes in the BioCatalogue base URL JOptionPane.showMessageDialog(this, "You have updated the Service Catalogue base URL.\n" + "This does not take effect until you restart Taverna.", "Service catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); } // the new base URL seems to be valid - can save it into config // settings configuration.setProperty(BioCataloguePluginConfiguration.SERVICE_CATALOGUE_BASE_URL, candidateBaseURL); /* // also update the base URL in the BioCatalogueClient BioCatalogueClient.getInstance() .setBaseURL(candidateBaseURL);*/ } }
From source file:edu.harvard.mcz.imagecapture.ui.ButtonEditor.java
@Override public void actionPerformed(ActionEvent e) { // Action might not be event_button_pressed on all systems. log.debug("Button event actionCommand: " + e.getActionCommand()); if (e.getActionCommand().equals(EVENT_PRESSED)) { // Event is a click on the cell // Identify the row that was clicked on. JTable table = (JTable) ((JButton) e.getSource()).getParent(); log.debug(e.getSource());/*from w w w . j a v a 2s .co m*/ log.debug(table); int row = table.getEditingRow(); // Stop editing - note, we need to have gotten e.getSource.getParent and getEditingRow first. fireEditingStopped(); //Make the renderer reappear. Singleton.getSingletonInstance().getMainFrame() .setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); switch (formToOpen) { case OPEN_SPECIMEN_DETAILS: // Load the selected specimen record from its ID (the data value behind the button). //SpecimenLifeCycle sls = new SpecimenLifeCycle(); //Specimen specimen = sls.findById((Long)targetId); //if (specimen!=null) { if (targetId != null) { // a specimen with this ID exists, bring up the details editor. try { //SpecimenControler sc = new SpecimenControler(specimen); if (((Specimen) targetId).getSpecimenId() != null) { if (((Specimen) targetId).isStateDone()) { // Specimens in state_done are no longer editable JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), "This Specimen record has been migrated and can no longer be edited here [" + ((Specimen) targetId).getLoadFlags() + "].\nSee: http://mczbase.mcz.harvard.edu/guid/MCZ:Ent:" + ((Specimen) targetId).getCatNum(), "Migrated Specimen", JOptionPane.WARNING_MESSAGE); } else { // Specimen is still editable if (table != null) { // Pass the specimen object for the row, the table model, and the row number on to the specimen controler. try { SpecimenControler sc = new SpecimenControler((Specimen) targetId, (SpecimenListTableModel) table.getModel(), table, row); if (table.getParent().getParent().getParent().getParent() .getClass() == SpecimenBrowser.class) { sc.addListener((DataChangeListener) table.getParent()); } else { Component x = table; boolean done = false; while (!done) { log.debug(x.getParent()); x = x.getParent(); if (x.getClass() == SpecimenBrowser.class) { sc.addListener((DataChangeListener) x); done = true; } } } sc.displayInEditor(); } catch (java.lang.ClassCastException eNotSp) { // Request isn't coming from a SpecimenListTableModel // View just the specimen record. SpecimenControler sc = new SpecimenControler((Specimen) targetId); sc.displayInEditor(); } } else { log.debug(e.getSource()); //SpecimenControler sc = new SpecimenControler((Specimen)targetId); //sc.displayInEditor(); } } } else { log.debug("User clicked on table row containing a new Specimen()"); JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), "No Specimen for this image", "Load Specimen Failed", JOptionPane.WARNING_MESSAGE); } } catch (NoSuchRecordException e1) { log.error("Tested for specimen!=null, but SpecimenControler threw null specimen exception"); log.error(e1); } } else { log.debug("No matches found to specimen id=" + targetId); // TODO: Create new specimen record and bring up dialog JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), "No specimen record."); } break; case OPEN_TEMPLATE: // Load the selected specimen record from its ID (the data value behind the button). try { // a template with this targetID exists, display it. ((PositionTemplateEditor) parentComponent).setTemplate((String) targetId); } catch (NoSuchTemplateException e1) { log.error("No such template on button press on a template in list."); log.error(e1); log.trace(e1); } break; case OPEN_USER: //TODO: tie to user log.debug("Open user"); ((UserListBrowser) parentComponent).getEditUserPanel().setUser((Users) targetId); break; case OPEN_SPECIMEN_VERBATIM: log.debug("Open Verbatim Transcription"); SpecimenLifeCycle sls = new SpecimenLifeCycle(); List<Specimen> toTranscribe = sls.findForVerbatim(((GenusSpeciesCount) targetId).getGenus(), ((GenusSpeciesCount) targetId).getSpecificEpithet(), WorkFlowStatus.STAGE_1); log.debug(toTranscribe.size()); SpecimenListTableModel stm = new SpecimenListTableModel(toTranscribe); JTable stable = new JTable(); stable.setModel(stm); SpecimenControler verbCont; try { verbCont = new SpecimenControler(toTranscribe.get(0), stm, stable, 0); VerbatimCaptureDialog dialog = new VerbatimCaptureDialog(toTranscribe.get(0), verbCont); dialog.setVisible(true); } catch (NoSuchRecordException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } break; case OPEN_VERBATIM_CLASSIFY: log.debug("Open Verbatim Classify dialog"); try { VerbatimClassifyDialog dialog = new VerbatimClassifyDialog( (VerbatimCount) table.getModel().getValueAt(row, 0)); dialog.setVisible(true); } catch (ClassCastException e1) { log.error(e1.getMessage(), e1); } break; case ACTION_CANCEL_JOB: log.debug("Action Cancel requested on job " + targetId); Singleton.getSingletonInstance().getJobList().getJobAt((Integer) targetId).cancel(); break; case OPEN_SPECIMENPARTATTRIBUTES: SpecimenPartAttributeDialog attrDialog = new SpecimenPartAttributeDialog((SpecimenPart) targetId); attrDialog.setVisible(true); break; } Singleton.getSingletonInstance().getMainFrame() .setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); System.gc(); } }
From source file:com.tiempometa.muestradatos.JMuestraDatos.java
private void configMenuItemActionPerformed(ActionEvent e) { if (ReaderContext.isUsbConnected() || ReaderContext.isFoxberryConnected()) { JOptionPane.showMessageDialog(this, "No se puede cambiar la configuracin mientras uno o ms lectores estn conectados", "Cambio de configuracin", JOptionPane.WARNING_MESSAGE); } else {//from www .j av a2 s . c o m JConfigDialog configDialog = new JConfigDialog(this, true); configDialog.setVisible(true); loadSettings(); } }
From source file:dbseer.gui.actions.ExplainChartAction.java
private void explain() { try {//from w w w . jav a 2 s .com if (panel.getAnomalyRegion().isEmpty()) { JOptionPane.showMessageDialog(null, "Please select an anomaly region.", "Warning", JOptionPane.WARNING_MESSAGE); return; } // console.setText("Analyzing data for explanation... "); DBSeerGUI.explainStatus.setText("Analyzing data for explanation..."); final StatisticalPackageRunner runner = DBSeerGUI.runner; final DBSeerExplainChartPanel explainPanel = this.panel; final String causalModelPath = this.causalModelPath; final JTextArea console = this.console; final ExplainChartAction action = this; SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { String normalIdx = ""; String anomalyIdx = ""; HashSet<Integer> normalRegion = new HashSet<Integer>(); HashSet<Integer> anomalyRegion = new HashSet<Integer>(); @Override protected Void doInBackground() throws Exception { for (Double d : explainPanel.getNormalRegion()) { normalRegion.add(d.intValue()); } for (Double d : explainPanel.getAnomalyRegion()) { anomalyRegion.add(d.intValue()); } for (Integer i : normalRegion) { normalIdx = normalIdx + i.toString() + " "; } for (Integer i : anomalyRegion) { anomalyIdx = anomalyIdx + i.toString() + " "; } runner.eval("normal_idx = [" + normalIdx + "];"); runner.eval("anomaly_idx = [" + anomalyIdx + "];"); runner.eval( "[predicates explanations] = explainPerformance(plotter.mv, anomaly_idx, normal_idx, '" + causalModelPath + "', 500, 0.2, 10);"); return null; } @Override protected void done() { try { DBSeerGUI.explainStatus.setText(""); printExplanations(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } }; worker.execute(); } catch (Exception e) { DBSeerExceptionHandler.handleException(e); } }
From source file:Data.java
/** * Creates a dataset, consisting of two series of monthly data. * * @return The dataset./*ww w . jav a 2 s .c o m*/ * @throws ClassNotFoundException */ private static XYDataset createDataset(Statement stmt) throws ClassNotFoundException { TimeSeries s1 = new TimeSeries("Humidit"); TimeSeries s2 = new TimeSeries("Temprature"); ResultSet rs = null; try { String sqlRequest = "SELECT * FROM `t_temphum`"; rs = stmt.executeQuery(sqlRequest); Double hum; Double temp; Timestamp date; while (rs.next()) { hum = rs.getDouble("tmp_humidity"); temp = rs.getDouble("tmp_temperature"); date = rs.getTimestamp("tmp_date"); if (tempUnit == "F") { temp = celsiusToFahrenheit(temp.toString()); } if (date != null) { s1.add(new Second(date), hum); s2.add(new Second(date), temp); } else { JOptionPane.showMessageDialog(panelPrincipal, "Il manque une date dans la dase de donne", "Date null", JOptionPane.WARNING_MESSAGE); } } rs.close(); } catch (SQLException e) { String exception = e.toString(); if (e.getErrorCode() == 0) { JOptionPane.showMessageDialog(panelPrincipal, "Le serveur met trop de temps rpondre ! Veuillez rssayer plus tard ou contacter un administrateur", "Connection timed out", JOptionPane.ERROR_MESSAGE); } else { JOptionPane.showMessageDialog(panelPrincipal, "Voici l'exception : " + exception, "Titre : exception", JOptionPane.ERROR_MESSAGE); // TODO Auto-generated catch block e.printStackTrace(); } } catch (Exception e) { String exception = e.toString(); JOptionPane.showMessageDialog(panelPrincipal, "Voici l'exception : " + exception, "Titre : exception", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } // ****************************************************************** // More than 150 demo applications are included with the JFreeChart // Developer Guide...for more information, see: // // > http://www.object-refinery.com/jfreechart/guide.html // // ****************************************************************** TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(s1); dataset.addSeries(s2); return dataset; }
From source file:net.sf.jabref.gui.preftabs.AppearancePrefsTab.java
@Override public void storeSettings() { // L&F/*from w w w . j a v a 2 s. c o m*/ prefs.putBoolean(JabRefPreferences.USE_DEFAULT_LOOK_AND_FEEL, !customLAF.isSelected()); prefs.put(JabRefPreferences.WIN_LOOK_AND_FEEL, classNamesLAF.getSelectedItem().toString()); if (customLAF.isSelected() == useDefaultLAF || !currentLAF.equals(classNamesLAF.getSelectedItem().toString())) { JOptionPane.showMessageDialog(null, Localization.lang("You have changed the look and feel setting.").concat(" ") .concat(Localization.lang("You must restart JabRef for this to come into effect.")), Localization.lang("Changed look and feel settings"), JOptionPane.WARNING_MESSAGE); } prefs.putBoolean(JabRefPreferences.TABLE_COLOR_CODES_ON, colorCodes.isSelected()); prefs.put(JabRefPreferences.FONT_FAMILY, usedFont.getFamily()); prefs.putInt(JabRefPreferences.FONT_STYLE, usedFont.getStyle()); prefs.putInt(JabRefPreferences.FONT_SIZE, usedFont.getSize()); prefs.putBoolean(JabRefPreferences.OVERRIDE_DEFAULT_FONTS, overrideFonts.isSelected()); GUIGlobals.currentFont = usedFont; colorPanel.storeSettings(); prefs.putBoolean(JabRefPreferences.TABLE_SHOW_GRID, showGrid.isSelected()); try { int size = Integer.parseInt(fontSize.getText()); if ((overrideFonts.isSelected() != oldOverrideFontSize) || (size != oldMenuFontSize)) { prefs.putInt(JabRefPreferences.MENU_FONT_SIZE, size); JOptionPane.showMessageDialog(null, Localization.lang("You have changed the menu and label font size.").concat(" ") .concat(Localization.lang("You must restart JabRef for this to come into effect.")), Localization.lang("Changed font settings"), JOptionPane.WARNING_MESSAGE); } } catch (NumberFormatException ex) { LOGGER.info("Invalid font size", ex); } try { int padding = Integer.parseInt(rowPadding.getText()); prefs.putInt(JabRefPreferences.TABLE_ROW_PADDING, padding); } catch (NumberFormatException ex) { LOGGER.info("Invalid row padding", ex); } }
From source file:net.sf.jabref.exporter.SaveDatabaseAction.java
private boolean saveDatabase(File file, boolean selectedOnly, Charset encoding) throws SaveException { SaveSession session;/*from w ww. jav a 2 s . c om*/ frame.block(); try { SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs) .withEncoding(encoding); BibDatabaseWriter databaseWriter = new BibDatabaseWriter(); if (selectedOnly) { session = databaseWriter.savePartOfDatabase(panel.getBibDatabaseContext(), prefs, panel.getSelectedEntries()); } else { session = databaseWriter.saveDatabase(panel.getBibDatabaseContext(), prefs); } panel.registerUndoableChanges(session); } catch (UnsupportedCharsetException ex2) { JOptionPane.showMessageDialog(frame, Localization.lang("Could not save file.") + Localization .lang("Character encoding '%0' is not supported.", encoding.displayName()), Localization.lang("Save database"), JOptionPane.ERROR_MESSAGE); throw new SaveException("rt"); } catch (SaveException ex) { if (ex == SaveException.FILE_LOCKED) { throw ex; } if (ex.specificEntry()) { // Error occured during processing of // be. Highlight it: int row = panel.mainTable.findEntry(ex.getEntry()); int topShow = Math.max(0, row - 3); panel.mainTable.setRowSelectionInterval(row, row); panel.mainTable.scrollTo(topShow); panel.showEntry(ex.getEntry()); } else { LOGGER.error("Problem saving file", ex); } JOptionPane.showMessageDialog(frame, Localization.lang("Could not save file.") + ".\n" + ex.getMessage(), Localization.lang("Save database"), JOptionPane.ERROR_MESSAGE); throw new SaveException("rt"); } finally { frame.unblock(); } boolean commit = true; if (!session.getWriter().couldEncodeAll()) { FormBuilder builder = FormBuilder.create() .layout(new FormLayout("left:pref, 4dlu, fill:pref", "pref, 4dlu, pref")); JTextArea ta = new JTextArea(session.getWriter().getProblemCharacters()); ta.setEditable(false); builder.add(Localization.lang("The chosen encoding '%0' could not encode the following characters:", session.getEncoding().displayName())).xy(1, 1); builder.add(ta).xy(3, 1); builder.add(Localization.lang("What do you want to do?")).xy(1, 3); String tryDiff = Localization.lang("Try different encoding"); int answer = JOptionPane.showOptionDialog(frame, builder.getPanel(), Localization.lang("Save database"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, new String[] { Localization.lang("Save"), tryDiff, Localization.lang("Cancel") }, tryDiff); if (answer == JOptionPane.NO_OPTION) { // The user wants to use another encoding. Object choice = JOptionPane.showInputDialog(frame, Localization.lang("Select encoding"), Localization.lang("Save database"), JOptionPane.QUESTION_MESSAGE, null, Encodings.ENCODINGS_DISPLAYNAMES, encoding); if (choice == null) { commit = false; } else { Charset newEncoding = Charset.forName((String) choice); return saveDatabase(file, selectedOnly, newEncoding); } } else if (answer == JOptionPane.CANCEL_OPTION) { commit = false; } } try { if (commit) { session.commit(file); panel.setEncoding(encoding); // Make sure to remember which encoding we used. } else { session.cancel(); } } catch (SaveException e) { int ans = JOptionPane.showConfirmDialog(null, Localization.lang("Save failed during backup creation") + ". " + Localization.lang("Save without backup?"), Localization.lang("Unable to create backup"), JOptionPane.YES_NO_OPTION); if (ans == JOptionPane.YES_OPTION) { session.setUseBackup(false); session.commit(file); panel.setEncoding(encoding); } else { commit = false; } } return commit; }
From source file:edu.gcsc.vrl.jfreechart.JFExport.java
/** * Show dialog for exporting JFreechart object. *///www. j av a 2s.c o m public void openExportDialog(JFreeChart jfreechart) { JFileChooser chooser = new JFileChooser(); String path0; File file; chooser.addChoosableFileFilter(new FileNameExtensionFilter("PDF Files", "pdf")); chooser.addChoosableFileFilter(new FileNameExtensionFilter("JPEG Files", "jpg")); chooser.addChoosableFileFilter(new FileNameExtensionFilter("PNG Files", "png")); chooser.addChoosableFileFilter(new FileNameExtensionFilter("EPS Files", "eps")); chooser.addChoosableFileFilter(new FileNameExtensionFilter("SVG Files", "svg")); chooser.setFileFilter(new FileNameExtensionFilter("PDF Files", "pdf")); int returnVal = chooser.showSaveDialog(null); String fd = chooser.getFileFilter().getDescription(); // Get selected FileFilter String filter_extension = null; if (fd.equals("PNG Files")) { filter_extension = "png"; } if (fd.equals("SVG Files")) { filter_extension = "svg"; } if (fd.equals("JPEG Files")) { filter_extension = "jpg"; } if (fd.equals("PDF Files")) { filter_extension = "pdf"; } if (fd.equals("EPS Files")) { filter_extension = "eps"; } // Cancel if (returnVal == JFileChooser.CANCEL_OPTION) { return; } // OK if (returnVal == JFileChooser.APPROVE_OPTION) { path0 = chooser.getSelectedFile().getAbsolutePath(); //System.out.println(path0); try { file = new File(path0); // Get extension (if any) String ext = JFUtils.getExtension(file); // No extension -> use selected Filter if (ext == null) { file = new File(path0 + "." + filter_extension); ext = filter_extension; } // File exists - overwrite ? if (file.exists()) { Object[] options = { "OK", "CANCEL" }; int answer = JOptionPane.showOptionDialog(null, "File exists - Overwrite ?", "Warning", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); if (answer != JOptionPane.YES_OPTION) { return; } //System.out.println(answer+""); } // Export file export(file, jfreechart); } catch (Exception f) { // I/O - Error } } }
From source file:be.vds.jtbdive.client.view.core.dive.profile.DiveProfileGraphicDetailPanel.java
private Component createImportButton() { JButton b = new JButton(new AbstractAction(null, UIAgent.getInstance().getIcon(UIAgent.ICON_IMPORT_24)) { private static final long serialVersionUID = 985413615438877711L; @Override//from ww w.ja va 2 s .co m public void actionPerformed(ActionEvent e) { JFileChooser ch = new JFileChooser(); ch.setFileFilter(new ExtensionFilter("xls", "Excel File")); int i = ch.showOpenDialog(null); if (i == JFileChooser.APPROVE_OPTION) { DiveProfileExcelParser p = new DiveProfileExcelParser(); try { File f = ch.getSelectedFile(); DiveProfile dp = p.read(f); I18nResourceManager i18n = I18nResourceManager.sharedInstance(); int yes = JOptionPane.showConfirmDialog(DiveProfileGraphicDetailPanel.this, i18n.getString("overwritte.diveprofile.confirm"), i18n.getString("confirmation"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (yes == JOptionPane.YES_OPTION) { currentDive.setDiveProfile(dp); setDiveProfile(dp, currentDive); logBookManagerFacade.setDiveChanged(currentDive); } } catch (IOException e1) { ExceptionDialog.showDialog(e1, DiveProfileGraphicDetailPanel.this); LOGGER.error(e1.getMessage()); } } } }); b.setToolTipText("Import"); return b; }
From source file:ExpenseReport.java
public void setValueAt(Object value, int nRow, int nCol) { if (nRow < 0 || nRow >= getRowCount()) return;/*from www .j a v a 2 s . com*/ ExpenseData row = (ExpenseData) m_vector.elementAt(nRow); String svalue = value.toString(); switch (nCol) { case COL_DATE: Date date = null; try { date = m_frm.parse(svalue); } catch (java.text.ParseException ex) { date = null; } if (date == null) { JOptionPane.showMessageDialog(null, svalue + " is not a valid date", "Warning", JOptionPane.WARNING_MESSAGE); return; } row.m_date = date; break; case COL_AMOUNT: try { row.m_amount = new Double(svalue); } catch (NumberFormatException e) { break; } m_parent.calcTotal(); break; case COL_CATEGORY: for (int k = 0; k < CATEGORIES.length; k++) if (svalue.equals(CATEGORIES[k])) { row.m_category = new Integer(k); break; } break; case COL_APPROVED: row.m_approved = (Boolean) value; break; case COL_DESCR: row.m_description = svalue; break; } }