List of usage examples for javax.swing JFileChooser JFileChooser
public JFileChooser()
JFileChooser
pointing to the user's default directory. From source file:be.fedict.eid.tsl.tool.SignSelectPkcs11FinishablePanel.java
@Override public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Select PKCS#11 library"); int returnValue = fileChooser.showOpenDialog(null); if (JFileChooser.APPROVE_OPTION == returnValue) { String pkcs11Library = fileChooser.getSelectedFile().getAbsolutePath(); this.pkcs11TextField.setText(pkcs11Library); }//from w w w .j av a 2 s. c o m }
From source file:XPathTest.java
/** * Open a file and load the document. *///from www . ja v a 2s . c o m public void openFile() { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); chooser.setFileFilter(new javax.swing.filechooser.FileFilter() { public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".xml"); } public String getDescription() { return "XML files"; } }); int r = chooser.showOpenDialog(this); if (r != JFileChooser.APPROVE_OPTION) return; File f = chooser.getSelectedFile(); try { byte[] bytes = new byte[(int) f.length()]; new FileInputStream(f).read(bytes); docText.setText(new String(bytes)); doc = builder.parse(f); } catch (IOException e) { JOptionPane.showMessageDialog(this, e); } catch (SAXException e) { JOptionPane.showMessageDialog(this, e); } }
From source file:de.fhbingen.wbs.wpOverview.tabs.APCalendarPanel.java
/** * Initialize the work package calendar panel inclusive the listeners. *///w w w .j av a 2 s .c om private void init() { List<Workpackage> userWp = new ArrayList<Workpackage>(WpManager.getUserWp(WPOverview.getUser())); Collections.sort(userWp, new APLevelComparator()); dataset = createDataset(userWp); chart = createChart(dataset); final ChartPanel chartPanel = new ChartPanel(chart); final JPopupMenu popup = new JPopupMenu(); JMenuItem miSave = new JMenuItem(LocalizedStrings.getButton().save(LocalizedStrings.getWbs().timeLine())); miSave.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new ExtensionAndFolderFilter("jpg", "jpeg")); //NON-NLS chooser.setSelectedFile(new File("chart-" //NON-NLS + System.currentTimeMillis() + ".jpg")); int returnVal = chooser.showSaveDialog(reference); if (returnVal == JFileChooser.APPROVE_OPTION) { try { File outfile = chooser.getSelectedFile(); ChartUtilities.saveChartAsJPEG(outfile, chart, chartPanel.getWidth(), chartPanel.getWidth()); Controller.showMessage( LocalizedStrings.getMessages().timeLineSaved(outfile.getCanonicalPath())); } catch (IOException e) { Controller.showError(LocalizedStrings.getErrorMessages().timeLineExportError()); } } } }); popup.add(miSave); chartPanel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3) { popup.show(e.getComponent(), e.getX(), e.getY()); } } }); chartPanel.setMinimumDrawHeight(50 + 15 * userWp.size()); chartPanel.setMaximumDrawHeight(50 + 15 * userWp.size()); chartPanel.setMaximumDrawWidth(9999); chartPanel.setPreferredSize( new Dimension((int) chartPanel.getPreferredSize().getWidth(), 50 + 15 * userWp.size())); chartPanel.setPopupMenu(null); this.setLayout(new BorderLayout()); this.removeAll(); JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.weightx = 1; constraints.weighty = 1; constraints.anchor = GridBagConstraints.NORTHWEST; panel.add(chartPanel, constraints); panel.setBackground(Color.white); this.add(panel, BorderLayout.CENTER); GanttRenderer.setDefaultShadowsVisible(false); GanttRenderer.setDefaultBarPainter(new BarPainter() { @Override public void paintBar(final Graphics2D g, final BarRenderer arg1, final int row, final int col, final RectangularShape rect, final RectangleEdge arg5) { String wpName = (String) dataset.getColumnKey(col); int i = 0; int spaceCount = 0; while (wpName.charAt(i++) == ' ' && spaceCount < 17) { spaceCount++; } g.setColor(new Color(spaceCount * 15, spaceCount * 15, spaceCount * 15)); g.fill(rect); g.setColor(Color.black); g.setStroke(new BasicStroke()); g.draw(rect); } @Override public void paintBarShadow(final Graphics2D arg0, final BarRenderer arg1, final int arg2, final int arg3, final RectangularShape arg4, final RectangleEdge arg5, final boolean arg6) { } }); ((CategoryPlot) chart.getPlot()).setRenderer(new GanttRenderer() { private static final long serialVersionUID = -6078915091070733812L; public void drawItem(final Graphics2D g2, final CategoryItemRendererState state, final Rectangle2D dataArea, final CategoryPlot plot, final CategoryAxis domainAxis, final ValueAxis rangeAxis, final CategoryDataset dataset, final int row, final int column, final int pass) { super.drawItem(g2, state, dataArea, plot, domainAxis, rangeAxis, dataset, row, column, pass); } }); }
From source file:edu.harvard.mcz.imagecapture.loader.JobVerbatimFieldLoad.java
@Override public void start() { startDateTime = new Date(); Singleton.getSingletonInstance().getJobList().addJob((RunnableJob) this); runStatus = RunStatus.STATUS_RUNNING; String selectedFilename = ""; if (file == null) { final JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); if (Singleton.getSingletonInstance().getProperties().getProperties() .getProperty(ImageCaptureProperties.KEY_LASTLOADPATH) != null) { fileChooser.setCurrentDirectory(new File(Singleton.getSingletonInstance().getProperties() .getProperties().getProperty(ImageCaptureProperties.KEY_LASTLOADPATH))); }/* www . j a va 2 s. c om*/ int returnValue = fileChooser.showOpenDialog(Singleton.getSingletonInstance().getMainFrame()); if (returnValue == JFileChooser.APPROVE_OPTION) { file = fileChooser.getSelectedFile(); } } if (file != null) { log.debug("Selected file to load: " + file.getName() + "."); if (file.exists() && file.isFile() && file.canRead()) { // Save location Singleton.getSingletonInstance().getProperties().getProperties() .setProperty(ImageCaptureProperties.KEY_LASTLOADPATH, file.getPath()); selectedFilename = file.getName(); String[] headers = new String[] {}; CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(headers); int rows = 0; try { rows = readRows(file, csvFormat); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), "Unable to load data, file not found: " + e.getMessage(), "Error: File Not Found", JOptionPane.OK_OPTION); errors.append("File not found ").append(e.getMessage()).append("\n"); log.error(e.getMessage(), e); } catch (IOException e) { errors.append("Error loading csv format, trying tab delimited: ").append(e.getMessage()) .append("\n"); log.debug(e.getMessage()); try { // try reading as tab delimited format, if successful, use that format. CSVFormat tabFormat = CSVFormat.newFormat('\t').withIgnoreSurroundingSpaces(true) .withHeader(headers).withQuote('"'); rows = readRows(file, tabFormat); csvFormat = tabFormat; } catch (IOException e1) { errors.append("Error Loading data: ").append(e1.getMessage()).append("\n"); log.error(e.getMessage(), e1); } } try { Reader reader = new FileReader(file); CSVParser csvParser = new CSVParser(reader, csvFormat); Map<String, Integer> csvHeader = csvParser.getHeaderMap(); headers = new String[csvHeader.size()]; int i = 0; for (String header : csvHeader.keySet()) { headers[i++] = header; log.debug(header); } boolean okToRun = true; //TODO: Work picking/checking responsibility into a FieldLoaderWizard List<String> headerList = Arrays.asList(headers); if (!headerList.contains("barcode")) { log.error("Input file " + file.getName() + " header does not contain required field 'barcode'."); // no barcode field, we can't match the input to specimen records. errors.append("Field \"barcode\" not found in csv file headers. Unable to load data.") .append("\n"); okToRun = false; } if (okToRun) { Iterator<CSVRecord> iterator = csvParser.iterator(); FieldLoader fl = new FieldLoader(); if (headerList.size() == 3 && headerList.contains("verbatimUnclassifiedText") && headerList.contains("questions") && headerList.contains("barcode")) { log.debug("Input file matches case 1: Unclassified text only."); // Allowed case 1a: unclassified text only int confirm = JOptionPane.showConfirmDialog( Singleton.getSingletonInstance().getMainFrame(), "Confirm load from file " + selectedFilename + " (" + rows + " rows) with just barcode and verbatimUnclassifiedText", "Verbatim unclassified Field found for load", JOptionPane.OK_CANCEL_OPTION); if (confirm == JOptionPane.OK_OPTION) { String barcode = ""; int lineNumber = 0; while (iterator.hasNext()) { lineNumber++; counter.incrementSpecimens(); CSVRecord record = iterator.next(); try { String verbatimUnclassifiedText = record.get("verbatimUnclassifiedText"); barcode = record.get("barcode"); String questions = record.get("questions"); fl.load(barcode, verbatimUnclassifiedText, questions, true); counter.incrementSpecimensUpdated(); } catch (IllegalArgumentException e) { RunnableJobError error = new RunnableJobError(file.getName(), barcode, Integer.toString(lineNumber), e.getClass().getSimpleName(), e, RunnableJobError.TYPE_LOAD_FAILED); counter.appendError(error); log.error(e.getMessage(), e); } catch (LoadException e) { RunnableJobError error = new RunnableJobError(file.getName(), barcode, Integer.toString(lineNumber), e.getClass().getSimpleName(), e, RunnableJobError.TYPE_LOAD_FAILED); counter.appendError(error); log.error(e.getMessage(), e); } percentComplete = (int) ((lineNumber * 100f) / rows); this.setPercentComplete(percentComplete); } } else { errors.append("Load canceled by user.").append("\n"); } } else if (headerList.size() == 4 && headerList.contains("verbatimUnclassifiedText") && headerList.contains("questions") && headerList.contains("barcode") && headerList.contains("verbatimClusterIdentifier")) { log.debug( "Input file matches case 1: Unclassified text only (with cluster identifier)."); // Allowed case 1b: unclassified text only (including cluster identifier) int confirm = JOptionPane.showConfirmDialog( Singleton.getSingletonInstance().getMainFrame(), "Confirm load from file " + selectedFilename + " (" + rows + " rows) with just barcode and verbatimUnclassifiedText", "Verbatim unclassified Field found for load", JOptionPane.OK_CANCEL_OPTION); if (confirm == JOptionPane.OK_OPTION) { String barcode = ""; int lineNumber = 0; while (iterator.hasNext()) { lineNumber++; counter.incrementSpecimens(); CSVRecord record = iterator.next(); try { String verbatimUnclassifiedText = record.get("verbatimUnclassifiedText"); String verbatimClusterIdentifier = record.get("verbatimClusterIdentifier"); barcode = record.get("barcode"); String questions = record.get("questions"); fl.load(barcode, verbatimUnclassifiedText, verbatimClusterIdentifier, questions, true); counter.incrementSpecimensUpdated(); } catch (IllegalArgumentException e) { RunnableJobError error = new RunnableJobError(file.getName(), barcode, Integer.toString(lineNumber), e.getClass().getSimpleName(), e, RunnableJobError.TYPE_LOAD_FAILED); counter.appendError(error); log.error(e.getMessage(), e); } catch (LoadException e) { RunnableJobError error = new RunnableJobError(file.getName(), barcode, Integer.toString(lineNumber), e.getClass().getSimpleName(), e, RunnableJobError.TYPE_LOAD_FAILED); counter.appendError(error); log.error(e.getMessage(), e); } percentComplete = (int) ((lineNumber * 100f) / rows); this.setPercentComplete(percentComplete); } } else { errors.append("Load canceled by user.").append("\n"); } } else if (headerList.size() == 8 && headerList.contains("verbatimUnclassifiedText") && headerList.contains("questions") && headerList.contains("barcode") && headerList.contains("verbatimLocality") && headerList.contains("verbatimDate") && headerList.contains("verbatimNumbers") && headerList.contains("verbatimCollector") && headerList.contains("verbatimCollection")) { // Allowed case two, transcription into verbatim fields, must be exact list of all // verbatim fields, not including cluster identifier or other metadata. log.debug("Input file matches case 2: Full list of verbatim fields."); int confirm = JOptionPane.showConfirmDialog( Singleton.getSingletonInstance().getMainFrame(), "Confirm load from file " + selectedFilename + " (" + rows + " rows) with just barcode and verbatim fields.", "Verbatim Fields found for load", JOptionPane.OK_CANCEL_OPTION); if (confirm == JOptionPane.OK_OPTION) { String barcode = ""; int lineNumber = 0; while (iterator.hasNext()) { lineNumber++; counter.incrementSpecimens(); CSVRecord record = iterator.next(); try { String verbatimLocality = record.get("verbatimLocality"); String verbatimDate = record.get("verbatimDate"); String verbatimCollector = record.get("verbatimCollector"); String verbatimCollection = record.get("verbatimCollection"); String verbatimNumbers = record.get("verbatimNumbers"); String verbatimUnclasifiedText = record.get("verbatimUnclassifiedText"); barcode = record.get("barcode"); String questions = record.get("questions"); fl.load(barcode, verbatimLocality, verbatimDate, verbatimCollector, verbatimCollection, verbatimNumbers, verbatimUnclasifiedText, questions); counter.incrementSpecimensUpdated(); } catch (IllegalArgumentException e) { RunnableJobError error = new RunnableJobError(file.getName(), barcode, Integer.toString(lineNumber), e.getClass().getSimpleName(), e, RunnableJobError.TYPE_LOAD_FAILED); counter.appendError(error); log.error(e.getMessage(), e); } catch (LoadException e) { RunnableJobError error = new RunnableJobError(file.getName(), barcode, Integer.toString(lineNumber), e.getClass().getSimpleName(), e, RunnableJobError.TYPE_LOAD_FAILED); counter.appendError(error); log.error(e.getMessage(), e); } percentComplete = (int) ((lineNumber * 100f) / rows); this.setPercentComplete(percentComplete); } } else { errors.append("Load canceled by user.").append("\n"); } } else { // allowed case three, transcription into arbitrary sets verbatim or other fields log.debug("Input file case 3: Arbitrary set of fields."); // Check column headers before starting run. boolean headersOK = false; try { HeaderCheckResult headerCheck = fl.checkHeaderList(headerList); if (headerCheck.isResult()) { int confirm = JOptionPane.showConfirmDialog( Singleton.getSingletonInstance().getMainFrame(), "Confirm load from file " + selectedFilename + " (" + rows + " rows) with headers: \n" + headerCheck.getMessage().replaceAll(":", ":\n"), "Fields found for load", JOptionPane.OK_CANCEL_OPTION); if (confirm == JOptionPane.OK_OPTION) { headersOK = true; } else { errors.append("Load canceled by user.").append("\n"); } } else { int confirm = JOptionPane.showConfirmDialog( Singleton.getSingletonInstance().getMainFrame(), "Problem found with headers in file, try to load anyway?\nHeaders: \n" + headerCheck.getMessage().replaceAll(":", ":\n"), "Problem in fields for load", JOptionPane.OK_CANCEL_OPTION); if (confirm == JOptionPane.OK_OPTION) { headersOK = true; } else { errors.append("Load canceled by user.").append("\n"); } } } catch (LoadException e) { errors.append("Error loading data: \n").append(e.getMessage()).append("\n"); JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), e.getMessage().replaceAll(":", ":\n"), "Error Loading Data: Problem Fields", JOptionPane.ERROR_MESSAGE); log.error(e.getMessage(), e); } if (headersOK) { int lineNumber = 0; while (iterator.hasNext()) { lineNumber++; Map<String, String> data = new HashMap<String, String>(); CSVRecord record = iterator.next(); String barcode = record.get("barcode"); Iterator<String> hi = headerList.iterator(); boolean containsNonVerbatim = false; while (hi.hasNext()) { String header = hi.next(); // Skip any fields prefixed by the underscore character _ if (!header.equals("barcode") && !header.startsWith("_")) { data.put(header, record.get(header)); if (!header.equals("questions") && MetadataRetriever.isFieldExternallyUpdatable(Specimen.class, header) && MetadataRetriever.isFieldVerbatim(Specimen.class, header)) { containsNonVerbatim = true; } } } if (data.size() > 0) { try { boolean updated = false; if (containsNonVerbatim) { updated = fl.loadFromMap(barcode, data, WorkFlowStatus.STAGE_CLASSIFIED, true); } else { updated = fl.loadFromMap(barcode, data, WorkFlowStatus.STAGE_VERBATIM, true); } counter.incrementSpecimens(); if (updated) { counter.incrementSpecimensUpdated(); } } catch (HibernateException e1) { // Catch (should just be development) problems with the underlying query StringBuilder message = new StringBuilder(); message.append("Query Error loading row (").append(lineNumber) .append(")[").append(barcode).append("]") .append(e1.getMessage()); RunnableJobError err = new RunnableJobError(selectedFilename, barcode, Integer.toString(lineNumber), e1.getMessage(), e1, RunnableJobError.TYPE_LOAD_FAILED); counter.appendError(err); log.error(e1.getMessage(), e1); } catch (LoadException e) { StringBuilder message = new StringBuilder(); message.append("Error loading row (").append(lineNumber).append(")[") .append(barcode).append("]").append(e.getMessage()); RunnableJobError err = new RunnableJobError(selectedFilename, barcode, Integer.toString(lineNumber), e.getMessage(), e, RunnableJobError.TYPE_LOAD_FAILED); counter.appendError(err); // errors.append(message.append("\n").toString()); log.error(e.getMessage(), e); } } percentComplete = (int) ((lineNumber * 100f) / rows); this.setPercentComplete(percentComplete); } } else { String message = "Can't load data, problem with headers."; errors.append(message).append("\n"); log.error(message); } } } csvParser.close(); reader.close(); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), "Unable to load data, file not found: " + e.getMessage(), "Error: File Not Found", JOptionPane.OK_OPTION); errors.append("File not found ").append(e.getMessage()).append("\n"); log.error(e.getMessage(), e); } catch (IOException e) { errors.append("Error Loading data: ").append(e.getMessage()).append("\n"); log.error(e.getMessage(), e); } } } else { //TODO: handle error condition log.error("File selection cancelled by user."); } report(selectedFilename); done(); }
From source file:ac.kaist.ccs.presentation.CCSHubSelectionCoverage.java
public CCSHubSelectionCoverage(final String title, List<Double> coverSourceNum) { super(title); this.title = title; final XYDataset dataset = createDataset(coverSourceNum); final JFreeChart chart = createChart(dataset); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); final ChartPanel chartPanel = new ChartPanel(chart); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new BorderLayout()); JButton buttonExport = new JButton("Export"); buttonPanel.add("East", buttonExport); buttonExport.addActionListener(new ActionListener() { ChartPanel chartPanel;//from w w w . j a v a2s.c om public ActionListener init(ChartPanel chartPanel) { this.chartPanel = chartPanel; return this; } @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub Dimension size = chartPanel.getSize(); try { //String outPath = textFieldSelectPath.getText(); //String filename = "chromatography.png"; //String path = outPath+"/"+filename; JFileChooser fileChooser = new JFileChooser(); fileChooser.setCurrentDirectory(new File("/Users/mac/Desktop")); fileChooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter("JPEG", "jpeg")); int returnVal = fileChooser.showDialog(new JFrame(), "Open File Path"); if (returnVal == JFileChooser.APPROVE_OPTION) { String inputPath = fileChooser.getSelectedFile().getAbsolutePath(); if (!inputPath.endsWith(".jpeg")) inputPath = inputPath + ".jpeg"; OutputStream os = new FileOutputStream(inputPath); System.out.println(inputPath + "///" + size.width + " " + size.height); BufferedImage chartImage = chartPanel.getChart().createBufferedImage(size.width, size.height, null); ImageIO.write(chartImage, "png", os); os.close(); JOptionPane.showMessageDialog(null, "Chart image was saved in " + inputPath); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.init(chartPanel)); panel.add("Center", chartPanel); panel.add("South", buttonPanel); chartPanel.setPreferredSize(new java.awt.Dimension(700, 500)); setContentPane(panel); }
From source file:ac.kaist.ccs.presentation.CCSHubSelectionCost.java
public CCSHubSelectionCost(final String title, Map<Integer, List<Double>> data) { super(title); this.title = title; final XYDataset dataset = createDataset(data); final JFreeChart chart = createChart(dataset); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); final ChartPanel chartPanel = new ChartPanel(chart); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new BorderLayout()); JButton buttonExport = new JButton("Export"); buttonPanel.add("East", buttonExport); buttonExport.addActionListener(new ActionListener() { ChartPanel chartPanel;/*from w w w. jav a 2 s.c o m*/ public ActionListener init(ChartPanel chartPanel) { this.chartPanel = chartPanel; return this; } @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub Dimension size = chartPanel.getSize(); try { //String outPath = textFieldSelectPath.getText(); //String filename = "chromatography.png"; //String path = outPath+"/"+filename; JFileChooser fileChooser = new JFileChooser(); fileChooser.setCurrentDirectory(new File("/Users/mac/Desktop")); fileChooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter("JPEG", "jpeg")); int returnVal = fileChooser.showDialog(new JFrame(), "Open File Path"); if (returnVal == JFileChooser.APPROVE_OPTION) { String inputPath = fileChooser.getSelectedFile().getAbsolutePath(); if (!inputPath.endsWith(".jpeg")) inputPath = inputPath + ".jpeg"; OutputStream os = new FileOutputStream(inputPath); System.out.println(inputPath + "///" + size.width + " " + size.height); BufferedImage chartImage = chartPanel.getChart().createBufferedImage(size.width, size.height, null); ImageIO.write(chartImage, "png", os); os.close(); JOptionPane.showMessageDialog(null, "Chart image was saved in " + inputPath); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.init(chartPanel)); panel.add("Center", chartPanel); panel.add("South", buttonPanel); chartPanel.setPreferredSize(new java.awt.Dimension(700, 500)); setContentPane(panel); }
From source file:ac.kaist.ccs.presentation.CCSHubSelectionCo2Coverage.java
public CCSHubSelectionCo2Coverage(final String title, List<Double> coverSourceNum) { super(title); this.title = title; final XYDataset dataset = createDataset(coverSourceNum); final JFreeChart chart = createChart(dataset); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); final ChartPanel chartPanel = new ChartPanel(chart); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new BorderLayout()); JButton buttonExport = new JButton("Export"); buttonPanel.add("East", buttonExport); buttonExport.addActionListener(new ActionListener() { ChartPanel chartPanel;/*w w w. jav a2 s. c om*/ public ActionListener init(ChartPanel chartPanel) { this.chartPanel = chartPanel; return this; } @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub Dimension size = chartPanel.getSize(); try { //String outPath = textFieldSelectPath.getText(); //String filename = "chromatography.png"; //String path = outPath+"/"+filename; JFileChooser fileChooser = new JFileChooser(); fileChooser.setCurrentDirectory(new File("/Users/mac/Desktop")); fileChooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter("JPEG", "jpeg")); int returnVal = fileChooser.showDialog(new JFrame(), "Open File Path"); if (returnVal == JFileChooser.APPROVE_OPTION) { String inputPath = fileChooser.getSelectedFile().getAbsolutePath(); if (!inputPath.endsWith(".jpeg")) inputPath = inputPath + ".jpeg"; OutputStream os = new FileOutputStream(inputPath); System.out.println(inputPath + "///" + size.width + " " + size.height); BufferedImage chartImage = chartPanel.getChart().createBufferedImage(size.width, size.height, null); ImageIO.write(chartImage, "png", os); os.close(); JOptionPane.showMessageDialog(null, "Chart image was saved in " + inputPath); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.init(chartPanel)); panel.add("Center", chartPanel); panel.add("South", buttonPanel); chartPanel.setPreferredSize(new java.awt.Dimension(700, 500)); setContentPane(panel); }
From source file:com.haulmont.cuba.desktop.gui.components.DesktopExportDisplay.java
private void saveFileAction(String fileName, JFrame frame, ExportDataProvider dataProvider) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setSelectedFile(new File(fileName)); if (fileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); boolean success = saveFile(dataProvider, selectedFile); TopLevelFrame mainFrame = App.getInstance().getMainFrame(); if (success) { mainFrame.showNotification(messages.getMessage(DesktopExportDisplay.class, "export.saveSuccess"), Frame.NotificationType.TRAY); } else {/* w ww . j a va 2 s .c o m*/ mainFrame.showNotification(messages.getMessage(DesktopExportDisplay.class, "export.saveError"), Frame.NotificationType.ERROR); } } }
From source file:edmondskarp.Gui.EdmondsKarpGui.java
private EdmondsKarpGui() { try {//from w w w . ja v a 2 s. c om for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(EdmondsKarpGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(EdmondsKarpGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(EdmondsKarpGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(EdmondsKarpGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } initComponents(); this.addWindowListener(new WListener()); setupUndoHotkeys(); circles = new ArrayList<>(); chooser = new JFileChooser(); isSecond = false; isInDragging = false; pointTmp = new Point2D.Double(); }
From source file:com.github.cmisbox.ui.UI.java
public File getWatchFolder() { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.setAcceptAllFileFilterUsed(false); chooser.showOpenDialog(null);//ww w . ja v a 2s. c o m return chooser.getSelectedFile(); }