Example usage for javax.swing JFileChooser showSaveDialog

List of usage examples for javax.swing JFileChooser showSaveDialog

Introduction

In this page you can find the example usage for javax.swing JFileChooser showSaveDialog.

Prototype

public int showSaveDialog(Component parent) throws HeadlessException 

Source Link

Document

Pops up a "Save File" file chooser dialog.

Usage

From source file:org.omegat.gui.align.AlignPanelController.java

/**
 * Display the align tool. The tool is not modal, so this call will return immediately.
 * /* w w  w.  java 2 s. c  o  m*/
 * @param parent
 *            Parent window of the align tool
 */
public void show(Component parent) {
    frame = new AlignMenuFrame();
    frame.setTitle(OStrings.getString("ALIGNER_PANEL"));
    frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            closeFrame(frame);
        }
    });

    panel = new AlignPanel();

    ActionListener comparisonListener = e -> {
        ComparisonMode newValue = (ComparisonMode) ((JComboBox<?>) e.getSource()).getSelectedItem();
        if (newValue != aligner.comparisonMode && confirmReset(frame)) {
            aligner.comparisonMode = newValue;
            reloadBeads();
        } else {
            panel.comparisonComboBox.setSelectedItem(aligner.comparisonMode);
        }
    };
    panel.comparisonComboBox.addActionListener(comparisonListener);
    panel.comparisonComboBox.setRenderer(new EnumRenderer<ComparisonMode>("ALIGNER_ENUM_COMPARISON_MODE_"));

    ActionListener algorithmListener = e -> {
        AlgorithmClass newValue = (AlgorithmClass) ((JComboBox<?>) e.getSource()).getSelectedItem();
        if (newValue != aligner.algorithmClass && confirmReset(frame)) {
            aligner.algorithmClass = newValue;
            reloadBeads();
        } else {
            panel.algorithmComboBox.setSelectedItem(aligner.algorithmClass);
        }
    };
    panel.algorithmComboBox.addActionListener(algorithmListener);
    panel.algorithmComboBox.setRenderer(new EnumRenderer<AlgorithmClass>("ALIGNER_ENUM_ALGORITHM_CLASS_"));

    ActionListener calculatorListener = e -> {
        CalculatorType newValue = (CalculatorType) ((JComboBox<?>) e.getSource()).getSelectedItem();
        if (newValue != aligner.calculatorType && confirmReset(frame)) {
            aligner.calculatorType = newValue;
            reloadBeads();
        } else {
            panel.calculatorComboBox.setSelectedItem(aligner.calculatorType);
        }
    };
    panel.calculatorComboBox.addActionListener(calculatorListener);
    panel.calculatorComboBox.setRenderer(new EnumRenderer<CalculatorType>("ALIGNER_ENUM_CALCULATOR_TYPE_"));

    ActionListener counterListener = e -> {
        CounterType newValue = (CounterType) ((JComboBox<?>) e.getSource()).getSelectedItem();
        if (newValue != aligner.counterType && confirmReset(frame)) {
            aligner.counterType = newValue;
            reloadBeads();
        } else {
            panel.counterComboBox.setSelectedItem(aligner.counterType);
        }
    };
    panel.counterComboBox.addActionListener(counterListener);
    panel.counterComboBox.setRenderer(new EnumRenderer<CounterType>("ALIGNER_ENUM_COUNTER_TYPE_"));

    ActionListener segmentingListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            boolean newValue = ((AbstractButton) e.getSource()).isSelected();
            if (newValue != aligner.segment && confirmReset(frame)) {
                aligner.segment = newValue;
                reloadBeads();
            } else {
                panel.segmentingCheckBox.setSelected(aligner.segment);
                frame.segmentingItem.setSelected(aligner.segment);
            }
        }
    };
    panel.segmentingCheckBox.addActionListener(segmentingListener);
    frame.segmentingItem.addActionListener(segmentingListener);

    ActionListener segmentingRulesListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (confirmReset(frame)) {
                SegmentationCustomizer customizer = new SegmentationCustomizer(false, SRX.getDefault(),
                        Core.getSegmenter().getSRX(), null);
                if (customizer.show(frame)) {
                    customizedSRX = customizer.getResult();
                    Core.setSegmenter(new Segmenter(customizedSRX));
                    reloadBeads();
                }
            }
        }
    };
    panel.segmentingRulesButton.addActionListener(segmentingRulesListener);
    frame.segmentingRulesItem.addActionListener(segmentingRulesListener);

    ActionListener filterSettingsListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (confirmReset(frame)) {
                FiltersCustomizer customizer = new FiltersCustomizer(false,
                        FilterMaster.createDefaultFiltersConfig(), Core.getFilterMaster().getConfig(), null);
                if (customizer.show(frame)) {
                    customizedFilters = customizer.getResult();
                    Core.setFilterMaster(new FilterMaster(customizedFilters));
                    aligner.clearLoaded();
                    reloadBeads();
                }
            }
        }
    };
    panel.fileFilterSettingsButton.addActionListener(filterSettingsListener);
    frame.fileFilterSettingsItem.addActionListener(filterSettingsListener);

    TableCellRenderer renderer = new MultilineCellRenderer();
    panel.table.setDefaultRenderer(Object.class, renderer);
    panel.table.setDefaultRenderer(Boolean.class, renderer);
    panel.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            resizeRows(panel.table);
        }
    });

    ActionListener oneAdjustListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int[] rows = panel.table.getSelectedRows();
            int col = panel.table.getSelectedColumn();
            boolean up = e.getSource().equals(panel.moveUpButton) || e.getSource().equals(frame.moveUpItem);
            BeadTableModel model = (BeadTableModel) panel.table.getModel();
            if ((e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0) {
                int trgRow = up ? model.prevBeadFromRow(rows[0]) : model.nextBeadFromRow(rows[rows.length - 1]);
                moveRows(rows, col, trgRow);
            } else {
                int offset = up ? -1 : 1;
                slideRows(rows, col, offset);
            }
        }
    };
    panel.moveUpButton.addActionListener(oneAdjustListener);
    frame.moveUpItem.addActionListener(oneAdjustListener);
    panel.moveDownButton.addActionListener(oneAdjustListener);
    frame.moveDownItem.addActionListener(oneAdjustListener);

    ActionListener mergeListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int[] rows = panel.table.getSelectedRows();
            int col = panel.table.getSelectedColumn();
            BeadTableModel model = (BeadTableModel) panel.table.getModel();
            if (rows.length == 1) {
                rows = new int[] { rows[0], model.nextNonEmptyCell(rows[0], col) };
            }
            int beads = model.beadsInRowSpan(rows);
            if (beads < 1) {
                // Do nothing
            } else if (beads == 1) {
                mergeRows(rows, col);
            } else {
                moveRows(rows, col, rows[0]);
            }
        }
    };
    panel.mergeButton.addActionListener(mergeListener);
    frame.mergeItem.addActionListener(mergeListener);

    ActionListener splitListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int[] rows = panel.table.getSelectedRows();
            int col = panel.table.getSelectedColumn();
            BeadTableModel model = (BeadTableModel) panel.table.getModel();
            int beads = model.beadsInRowSpan(rows);
            if (beads != 1) {
                // Do nothing
            } else if (rows.length == 1) {
                splitRow(rows[0], col);
            } else {
                splitBead(rows, col);
            }
        }
    };
    panel.splitButton.addActionListener(splitListener);
    frame.splitItem.addActionListener(splitListener);

    ActionListener editListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            int row = panel.table.getSelectedRow();
            int col = panel.table.getSelectedColumn();
            editRow(row, col);
        }
    };
    panel.editButton.addActionListener(editListener);
    frame.editItem.addActionListener(editListener);

    ListSelectionListener selectionListener = new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            updateCommandAvailability(panel, frame);
        }
    };
    panel.table.getColumnModel().getSelectionModel().addListSelectionListener(selectionListener);
    panel.table.getSelectionModel().addListSelectionListener(selectionListener);

    ActionListener saveListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (!confirmSaveTMX(panel)) {
                return;
            }
            while (true) {
                JFileChooser chooser = new JFileChooser();
                chooser.setSelectedFile(new File(defaultSaveDir, getOutFileName()));
                chooser.setDialogTitle(OStrings.getString("ALIGNER_PANEL_DIALOG_SAVE"));
                if (JFileChooser.APPROVE_OPTION == chooser.showSaveDialog(frame)) {
                    File file = chooser.getSelectedFile();
                    if (file.isFile()) {
                        if (JOptionPane.OK_OPTION != JOptionPane.showConfirmDialog(frame,
                                StringUtil.format(OStrings.getString("ALIGNER_PANEL_DIALOG_OVERWRITE"),
                                        file.getName()),
                                OStrings.getString("ALIGNER_DIALOG_WARNING_TITLE"),
                                JOptionPane.WARNING_MESSAGE)) {
                            continue;
                        }
                    }
                    List<MutableBead> beads = ((BeadTableModel) panel.table.getModel()).getData();
                    try {
                        aligner.writePairsToTMX(file,
                                MutableBead.beadsToEntries(aligner.srcLang, aligner.trgLang, beads));
                        modified = false;
                    } catch (Exception ex) {
                        Log.log(ex);
                        JOptionPane.showMessageDialog(frame, OStrings.getString("ALIGNER_PANEL_SAVE_ERROR"),
                                OStrings.getString("ERROR_TITLE"), JOptionPane.ERROR_MESSAGE);
                    }
                }
                break;
            }
        }
    };
    panel.saveButton.addActionListener(saveListener);
    frame.saveItem.addActionListener(saveListener);

    ActionListener resetListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (confirmReset(frame)) {
                if (phase == Phase.ALIGN) {
                    aligner.restoreDefaults();
                }
                reloadBeads();
            }
        }
    };
    panel.resetButton.addActionListener(resetListener);
    frame.resetItem.addActionListener(resetListener);

    ActionListener reloadListener = e -> {
        if (confirmReset(frame)) {
            aligner.clearLoaded();
            reloadBeads();
        }
    };
    frame.reloadItem.addActionListener(reloadListener);

    ActionListener removeTagsListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            boolean newValue = ((AbstractButton) e.getSource()).isSelected();
            if (newValue != aligner.removeTags && confirmReset(frame)) {
                aligner.removeTags = newValue;
                aligner.clearLoaded();
                reloadBeads();
            } else {
                panel.removeTagsCheckBox.setSelected(aligner.removeTags);
                frame.removeTagsItem.setSelected(aligner.removeTags);
            }
        }
    };
    panel.removeTagsCheckBox.addActionListener(removeTagsListener);
    frame.removeTagsItem.addActionListener(removeTagsListener);

    panel.continueButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            phase = Phase.EDIT;
            updatePanel();
        }
    });

    ActionListener highlightListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            doHighlight = ((AbstractButton) e.getSource()).isSelected();
            updateHighlight();
        }
    };
    panel.highlightCheckBox.addActionListener(highlightListener);
    frame.highlightItem.addActionListener(highlightListener);

    ActionListener highlightPatternListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            PatternPanelController patternEditor = new PatternPanelController(highlightPattern);
            highlightPattern = patternEditor.show(frame);
            Preferences.setPreference(Preferences.ALIGNER_HIGHLIGHT_PATTERN, highlightPattern.pattern());
            updateHighlight();
        }
    };
    panel.highlightPatternButton.addActionListener(highlightPatternListener);
    frame.highlightPatternItem.addActionListener(highlightPatternListener);

    frame.markAcceptedItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setStatus(MutableBead.Status.ACCEPTED, panel.table.getSelectedRows());
        }
    });

    frame.markNeedsReviewItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setStatus(MutableBead.Status.NEEDS_REVIEW, panel.table.getSelectedRows());
        }
    });

    frame.clearMarkItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setStatus(MutableBead.Status.DEFAULT, panel.table.getSelectedRows());
        }
    });

    frame.toggleSelectedItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            toggleEnabled(panel.table.getSelectedRows());
        }
    });

    frame.closeItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            closeFrame(frame);
        }
    });

    frame.keepAllItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            toggleAllEnabled(true);
        }
    });

    frame.keepNoneItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            toggleAllEnabled(false);
        }
    });

    frame.realignPendingItem.addActionListener(e -> {
        realignPending();
    });

    frame.pinpointAlignStartItem.addActionListener(e -> {
        phase = Phase.PINPOINT;
        ppRow = panel.table.getSelectedRow();
        ppCol = panel.table.getSelectedColumn();
        panel.table.clearSelection();
        updatePanel();
    });

    frame.pinpointAlignEndItem.addActionListener(e -> {
        pinpointAlign(panel.table.getSelectedRow(), panel.table.getSelectedColumn());
    });

    frame.pinpointAlignCancelItem.addActionListener(e -> {
        phase = Phase.EDIT;
        ppRow = -1;
        ppCol = -1;
        panel.table.repaint();
        updatePanel();
    });

    panel.table.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (phase == Phase.PINPOINT) {
                JTable table = (JTable) e.getSource();
                int row = table.rowAtPoint(e.getPoint());
                int col = table.columnAtPoint(e.getPoint());
                pinpointAlign(row, col);
            }
        }
    });

    frame.resetItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() | KeyEvent.SHIFT_DOWN_MASK));
    frame.realignPendingItem.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_R, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    frame.saveItem.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    frame.closeItem.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_W, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));

    // emacs-like keys for table navigation
    // See javax.swing.plaf.BasicTableUI.Actions for supported action names.
    setKeyboardShortcut(panel.table, "selectNextRow", 'n');
    setKeyboardShortcut(panel.table, "selectNextRowExtendSelection", 'N');
    setKeyboardShortcut(panel.table, "selectPreviousRow", 'p');
    setKeyboardShortcut(panel.table, "selectPreviousRowExtendSelection", 'P');
    setKeyboardShortcut(panel.table, "selectNextColumn", 'f');
    setKeyboardShortcut(panel.table, "selectNextColumnExtendSelection", 'F');
    setKeyboardShortcut(panel.table, "selectPreviousColumn", 'b');
    setKeyboardShortcut(panel.table, "selectPreviousColumnExtendSelection", 'B');

    panel.table.setTransferHandler(new AlignTransferHandler());
    panel.table.addPropertyChangeListener("dropLocation", new DropLocationListener());
    if (Preferences.isPreference(Preferences.PROJECT_FILES_USE_FONT)) {
        try {
            String fontName = Preferences.getPreference(Preferences.TF_SRC_FONT_NAME);
            int fontSize = Integer.parseInt(Preferences.getPreference(Preferences.TF_SRC_FONT_SIZE));
            panel.table.setFont(new Font(fontName, Font.PLAIN, fontSize));
        } catch (Exception e) {
            Log.log(e);
        }
    }

    // Set initial state
    updateHighlight();
    updatePanel();
    reloadBeads();

    frame.add(panel);
    frame.pack();
    frame.setMinimumSize(frame.getSize());
    frame.setLocationRelativeTo(parent);
    frame.setVisible(true);
}

From source file:org.omegat.gui.dialogs.LogDialog.java

private void saveAsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveAsButtonActionPerformed
    String curDir = Preferences.getPreferenceDefault(Preferences.CURRENT_FOLDER,
            System.getProperty("user.home"));
    JFileChooser chooser = new JFileChooser();
    chooser.setSelectedFile(new File(curDir, Log.getLogFileName()));
    if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) {
        return;/*from  w  w  w. java2 s  .  c  o  m*/
    }
    File outFile = chooser.getSelectedFile();
    if (outFile.exists() && !FileCollisionDialog.promptToReplace(this, outFile.getName())) {
        return;
    }
    try {
        FileUtils.copyFile(new File(Log.getLogFilePath()), chooser.getSelectedFile());
    } catch (IOException ex) {
        Log.log(ex);
    }
    Preferences.setPreference(Preferences.CURRENT_FOLDER, outFile.getParent());
}

From source file:org.omelogic.tome.EpiTome.java

public void init() {
    backingGraph = null;//from w  w w .  j  a  va 2 s  . c  o  m
    tomeGraph = null;
    idFilter = null;

    JPanel tablePanel = new JPanel();
    tomeTable = new JTable();
    JScrollPane tomeTableScroller = new JScrollPane(tomeTable);
    tablePanel.setLayout(new BoxLayout(tablePanel, BoxLayout.PAGE_AXIS));
    tablePanel.add(tomeTableScroller);
    tomeProps = new JLabel("");

    JPanel tomePropsPanel = new JPanel(new BorderLayout());
    tomePropsPanel.add(tomeProps, BorderLayout.LINE_START);
    //tablePanel.add(tomeTableFixed);
    tablePanel.add(tomePropsPanel);
    //JScrollPane tablePanelScroller = new JScrollPane(tablePanel);
    tablePanel.setPreferredSize(new Dimension(300, 400));

    //####### CONTROLS #########################################
    JPanel controlPanel = new JPanel();
    JButton load = new JButton("LOAD");
    load.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent act) {
            JFileChooser chooser = new JFileChooser();
            chooser.setFileFilter(new SIFFileFilter());
            chooser.setMultiSelectionEnabled(false);
            int returnVal = chooser.showOpenDialog(tomeFrame);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());
            } else {
                return;
            }
            File sifFile = chooser.getSelectedFile();
            UndirectedSparseGraph result = null;
            try {
                result = SIFHandler.load(sifFile);
            } catch (Exception e) {
                System.out.println(e.toString());
            }
            System.out.println("Loaded file!");
            backingGraph = result;
            FilterDialog filterMe = new FilterDialog();
            idFilter = filterMe.getFilter();
            loadInitialGraph((UndirectedSparseGraph) TomeGraphUtilities.filterGraph(backingGraph, idFilter));

        }
    });

    JButton save = new JButton("SAVE");
    save.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent act) {
            if (tomeGraph == null) {
                JOptionPane.showMessageDialog(null, "No graph is loaded!", "ERROR!", JOptionPane.ERROR_MESSAGE);
                return;
            }
            JFileChooser chooser = new JFileChooser();
            if (((Double) ((HashMap<String, Double>) (tomeGraph.getUserDatum("GraphStatistics")))
                    .get("AveragePathLength")).isInfinite()) {
                JOptionPane.showMessageDialog(null,
                        "Graph is not fully connected! This renders most output useless. Try trimming the graph first...",
                        "ERROR!", JOptionPane.ERROR_MESSAGE);
                return;
            }

            int returnVal = chooser.showSaveDialog(EpiTome.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();

                FileOutputStream out; // declare a file output object
                PrintStream p; // declare a print stream object

                try {
                    // Create a new file output stream
                    out = new FileOutputStream(file);

                    // Connect print stream to the output stream
                    p = new PrintStream(out);

                    HashMap<String, Double> graphProps = (HashMap<String, Double>) tomeGraph
                            .getUserDatum("GraphStatistics");

                    p.println("#---SUMMARY---");
                    p.println("#NumNodes:\t" + tomeGraph.numVertices());
                    p.println("#NumEdges:\t" + tomeGraph.numEdges());
                    p.println("#ClustCoeff:\t" + graphProps.get(TomeGraphUtilities.CLUSTERING_COEFFICIENT));
                    p.println("#AvgPathLen:\t" + graphProps.get(TomeGraphUtilities.AVERAGE_PATH_LENGTH));
                    p.println("#AvgDegree:\t" + graphProps.get(TomeGraphUtilities.AVERAGE_DEGREE));
                    p.println("#-------------");
                    p.println("\n\n");

                    p.println("NodeID\tClustCoeff\tAvgPathLen\tAvgDegree");
                    Iterator<TomeVertex> vertIter = tomeGraph.getVertices().iterator();
                    while (vertIter.hasNext()) {
                        TomeVertex vert = vertIter.next();
                        p.println(vert.getID() + "\t" + vert.getClusteringCoefficient() + "\t"
                                + vert.getAverageDistance() + "\t" + vert.getDegree());
                    }

                    p.close();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Error writing to file!\n" + e.toString(), "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    });

    JButton trim = new JButton("TRIM");
    trim.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (tomeGraph == null) {
                JOptionPane.showMessageDialog(null, "No graph is loaded!", "ERROR!", JOptionPane.ERROR_MESSAGE);
                return;
            }
            TrimDialog trimMe = new TrimDialog();
            loadSubGraph(trimMe.getTrimmedGraph(tomeGraph));

        }
    });

    JButton rset = new JButton("RSET");
    rset.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (backingGraph == null) {
                JOptionPane.showMessageDialog(null, "No graph is loaded!", "ERROR!", JOptionPane.ERROR_MESSAGE);
                return;
            }
            loadInitialGraph((UndirectedSparseGraph) TomeGraphUtilities.filterGraph(backingGraph, idFilter));
        }
    });

    JButton view = new JButton("VIEW");
    view.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            if (tomeGraph == null) {
                JOptionPane.showMessageDialog(null, "No graph is loaded!", "ERROR!", JOptionPane.ERROR_MESSAGE);
                return;
            }
            GraphDialog graf = new GraphDialog(tomeGraph, getSelectedNodeSubGraph());
        }
    });

    JButton ctrl = new JButton("CTRL");
    ctrl.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (tomeGraph == null) {
                JOptionPane.showMessageDialog(null, "No graph is loaded!", "ERROR!", JOptionPane.ERROR_MESSAGE);
                return;
            }
            try {
                ControlsDialog ctrls = new ControlsDialog(tomeGraph, backingGraph, NUM_CONTROLS, NUM_BINS_MAX);
            } catch (Exception excep) {
            }
        }
    });

    JButton help = new JButton("HELP");
    help.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            HelpDialog.display();
        }
    });

    controlPanel.add(load);
    controlPanel.add(save);
    controlPanel.add(trim);
    controlPanel.add(rset);
    controlPanel.add(view);
    controlPanel.add(ctrl);
    controlPanel.add(help);

    //##########################################################

    Container content = tomeFrame.getContentPane();

    content.removeAll();
    content.add(tablePanel, BorderLayout.CENTER);
    content.add(controlPanel, BorderLayout.SOUTH);

}

From source file:org.owasp.jbrofuzz.fuzz.io.Save.java

/**
 * <p>Method for obtaining a file location, through a 
 * JFileChooser for the user to save a .jbrofuzz file.</p>
 * /*from w ww.j  a v a 2s .c  om*/
 * <p>In the event of an error or an exception, this
 * method returns null.</p>
 * 
 * @param mWindow
 * @return
 */
public static File showSaveDialog(JBroFuzzWindow mWindow) {

    final String dirString = JBroFuzz.PREFS.get(JBroFuzzPrefs.DIRS[2].getId(), System.getProperty("user.dir"));

    final File dirLocation = new File(dirString);
    JFileChooser fChooser;
    try {
        if (dirLocation.exists() && dirLocation.isDirectory()) {
            fChooser = new JFileChooser(dirString);
        } else {
            fChooser = new JFileChooser();
        }
    } catch (final SecurityException sException) {
        fChooser = new JFileChooser();
        Logger.log("A security exception occured, while attempting to save as to a directory", 4);
    }
    // Set the filter for the file extension
    fChooser.setFileFilter(new JBroFuzzFileFilter());
    // Talk to the user
    final int retValue = fChooser.showSaveDialog(mWindow);
    // If there is an approval or selection
    if (retValue == JFileChooser.APPROVE_OPTION) {

        File returnFile = fChooser.getSelectedFile();
        Logger.log("Saving: " + returnFile.getName(), 1);
        // 
        final String filePath = returnFile.getAbsolutePath().toLowerCase();
        if (!filePath.endsWith(".jbrofuzz")) {
            returnFile = new File(filePath + ".jbrofuzz");
        }

        if (returnFile.exists()) {

            final int overwrite = JOptionPane.showConfirmDialog(fChooser,
                    "File already exists. Do you \nwant to replace it?", " JBroFuzz - Save ",
                    JOptionPane.YES_NO_OPTION);

            // If the user does not want to overwrite, return null
            if (overwrite == JOptionPane.NO_OPTION) {
                return null;
            }
        }
        // Before returning the file, set the preference
        // for the parent directory
        final String parentDir = returnFile.getParent();
        if (parentDir != null) {
            JBroFuzz.PREFS.put(JBroFuzzPrefs.DIRS[2].getId(), parentDir);
        }

        return returnFile;
    }

    // If the user cancelled, return nulls
    return null;

}

From source file:org.parosproxy.paros.control.MenuFileControl.java

public void saveAsSession() {
    if (!informStopActiveActions()) {
        return;//from www.j  a  va2 s  .  c om
    }

    Session session = model.getSession();

    JFileChooser chooser = new JFileChooser(model.getOptionsParam().getUserDirectory());
    // ZAP: set session name as file name proposal
    File fileproposal = new File(session.getSessionName());
    if (session.getFileName() != null && session.getFileName().trim().length() > 0) {
        // if there is already a file name, use it
        fileproposal = new File(session.getFileName());
    }
    chooser.setSelectedFile(fileproposal);
    chooser.setFileFilter(new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            } else if (file.isFile() && file.getName().endsWith(".session")) {
                return true;
            }
            return false;
        }

        @Override
        public String getDescription() {
            // ZAP: Rebrand
            return Constant.messages.getString("file.format.zap.session");
        }
    });
    File file = null;
    int rc = chooser.showSaveDialog(view.getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        file = chooser.getSelectedFile();
        if (file == null) {
            return;
        }
        model.getOptionsParam().setUserDirectory(chooser.getCurrentDirectory());
        String fileName = file.getAbsolutePath();
        if (!fileName.endsWith(".session")) {
            fileName += ".session";
        }

        try {
            waitMessageDialog = view
                    .getWaitMessageDialog(Constant.messages.getString("menu.file.savingSession")); // ZAP: i18n
            control.saveSession(fileName, this);
            log.info("save as session file " + session.getFileName());
            waitMessageDialog.setVisible(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}

From source file:org.parosproxy.paros.control.MenuFileControl.java

public void saveSnapshot() {
    String activeActions = wrapEntriesInLiTags(control.getExtensionLoader().getActiveActions());
    if (!activeActions.isEmpty()) {
        view.showMessageDialog(Constant.messages.getString("menu.file.snapshot.activeactions", activeActions));
        return;//from w  w w  . ja va2 s  . c o m
    }

    Session session = model.getSession();

    JFileChooser chooser = new JFileChooser(model.getOptionsParam().getUserDirectory());
    // ZAP: set session name as file name proposal
    File fileproposal = new File(session.getSessionName());
    if (session.getFileName() != null && session.getFileName().trim().length() > 0) {
        String proposedFileName;
        // if there is already a file name, use it and add a timestamp
        proposedFileName = StringUtils.removeEnd(session.getFileName(), ".session");
        proposedFileName += "-" + dateFormat.format(new Date()) + ".session";
        fileproposal = new File(proposedFileName);
    }
    chooser.setSelectedFile(fileproposal);
    chooser.setFileFilter(new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            } else if (file.isFile() && file.getName().endsWith(".session")) {
                return true;
            }
            return false;
        }

        @Override
        public String getDescription() {
            return Constant.messages.getString("file.format.zap.session");
        }
    });
    File file = null;
    int rc = chooser.showSaveDialog(view.getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        file = chooser.getSelectedFile();
        if (file == null) {
            return;
        }
        model.getOptionsParam().setUserDirectory(chooser.getCurrentDirectory());
        String fileName = file.getAbsolutePath();
        if (!fileName.endsWith(".session")) {
            fileName += ".session";
        }

        try {
            waitMessageDialog = view
                    .getWaitMessageDialog(Constant.messages.getString("menu.file.savingSnapshot")); // ZAP: i18n
            control.snapshotSession(fileName, this);
            log.info("Snapshotting: " + session.getFileName() + " as " + fileName);
            waitMessageDialog.setVisible(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}

From source file:org.parosproxy.paros.extension.beanshell.BeanShellConsoleDialog.java

private JButton getBtnSave() {
    if (btnSave == null) {
        btnSave = new JButton();
        btnSave.setText("Save...");

        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                if (currentScriptFile != null) {
                    try {
                        saveScript(getBeanShellPanel().getTxtEditor().getText(), currentScriptFile);
                        getBeanShellPanel().setSaved(true);
                    } catch (IOException ee) {
                        ee.printStackTrace();
                    }//from  w  ww . j a va2 s  .  c o m

                } else {
                    JFileChooser fc = new JFileChooser(scriptsDir);
                    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
                    int result = fc.showSaveDialog(getBeanShellPanel());

                    if (result == JFileChooser.APPROVE_OPTION) {
                        try {
                            saveScript(getBeanShellPanel().getTxtEditor().getText(), fc.getSelectedFile());
                            getBeanShellPanel().setSaved(true);
                            currentScriptFile = fc.getSelectedFile();
                        } catch (IOException ee) {
                            ee.printStackTrace();
                        }
                    }
                }
            }
        });
    }
    return btnSave;
}

From source file:org.parosproxy.paros.extension.beanshell.BeanShellConsoleDialog.java

private JButton getBtnSaveAs() {
    if (btnSaveAs == null) {
        btnSaveAs = new JButton();
        btnSaveAs.setText("Save as...");

        btnSaveAs.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                JFileChooser fc = new JFileChooser(scriptsDir);
                fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
                int result = fc.showSaveDialog(getBeanShellPanel());
                if (result == JFileChooser.APPROVE_OPTION) {
                    try {
                        saveScript(getBeanShellPanel().getTxtEditor().getText(), fc.getSelectedFile());
                        getBeanShellPanel().setSaved(true);
                        currentScriptFile = fc.getSelectedFile();
                    } catch (IOException ee) {
                        ee.printStackTrace();
                    }//from   w w  w . j  a  v  a 2s  .  c o m
                }

            }
        });
    }
    return btnSaveAs;
}

From source file:org.parosproxy.paros.extension.history.PopupMenuExportMessage.java

private File getOutputFile() {

    JFileChooser chooser = new JFileChooser(extension.getModel().getOptionsParam().getUserDirectory());
    chooser.setFileFilter(new FileFilter() {
        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            } else if (file.isFile() && file.getName().endsWith(".txt")) {
                return true;
            }//from   w w w.ja v  a  2  s.co m
            return false;
        }

        public String getDescription() {
            return "ASCII text file";
        }
    });
    File file = null;
    int rc = chooser.showSaveDialog(extension.getView().getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        file = chooser.getSelectedFile();
        if (file == null) {
            return file;
        }
        extension.getModel().getOptionsParam().setUserDirectory(chooser.getCurrentDirectory());
        String fileName = file.getAbsolutePath();
        if (!fileName.endsWith(".txt")) {
            fileName += ".txt";
            file = new File(fileName);
        }
        return file;

    }
    return file;
}

From source file:org.parosproxy.paros.extension.history.PopupMenuExportResponse.java

private File getOutputFile(HttpMessage msg) {

    String filename = "";
    try {/*  w  w w .ja  va  2s  .c  o  m*/
        filename = msg.getRequestHeader().getURI().getPath();
        int pos = filename.lastIndexOf("/");
        filename = filename.substring(pos);
    } catch (Exception e) {
    }
    JFileChooser chooser = new JFileChooser(extension.getModel().getOptionsParam().getUserDirectory());
    if (filename.length() > 0) {
        chooser.setSelectedFile(new File(filename));
    }

    File file = null;
    int rc = chooser.showSaveDialog(extension.getView().getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        file = chooser.getSelectedFile();
        if (file == null) {
            return file;
        }

        extension.getModel().getOptionsParam().setUserDirectory(chooser.getCurrentDirectory());

        return file;

    }
    return file;
}