Example usage for javax.swing JFileChooser setMultiSelectionEnabled

List of usage examples for javax.swing JFileChooser setMultiSelectionEnabled

Introduction

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

Prototype

@BeanProperty(description = "Sets multiple file selection mode.")
public void setMultiSelectionEnabled(boolean b) 

Source Link

Document

Sets the file chooser to allow multiple file selections.

Usage

From source file:org.kse.gui.dialogs.sign.DSignMidlet.java

private void outputJadBrowsePressed() {
    JFileChooser chooser = FileChooserFactory.getJadFileChooser();

    File currentFile = new File(jtfOutputJad.getText());

    if (currentFile.getParentFile() != null && currentFile.getParentFile().exists()) {
        chooser.setCurrentDirectory(currentFile.getParentFile());
        chooser.setSelectedFile(currentFile);
    } else {/*from   w  w  w . j  a v  a2s.  c  o  m*/
        chooser.setCurrentDirectory(CurrentDirectory.get());
    }

    chooser.setDialogTitle(res.getString("DSignMidlet.ChooseOutputJad.Title"));

    chooser.setMultiSelectionEnabled(false);

    int rtnValue = JavaFXFileChooser.isFxAvailable() ? chooser.showSaveDialog(this)
            : chooser.showDialog(this, res.getString("DSignMidlet.OutputJadChooser.button"));
    if (rtnValue == JFileChooser.APPROVE_OPTION) {
        File chosenFile = chooser.getSelectedFile();
        CurrentDirectory.updateForFile(chosenFile);
        jtfOutputJad.setText(chosenFile.toString());
        jtfOutputJad.setCaretPosition(0);
    }
}

From source file:org.kse.gui.dialogs.sign.DSignMidlet.java

private void jarBrowsePressed() {
    JFileChooser chooser = FileChooserFactory.getArchiveFileChooser();

    File currentFile = new File(jtfJar.getText());

    if (currentFile.getParentFile() != null && currentFile.getParentFile().exists()) {
        chooser.setCurrentDirectory(currentFile.getParentFile());
    } else {//from ww  w.j  a va2  s. co m
        chooser.setCurrentDirectory(CurrentDirectory.get());
    }

    chooser.setDialogTitle(res.getString("DSignMidlet.ChooseJar.Title"));

    chooser.setMultiSelectionEnabled(false);

    int rtnValue = chooser.showDialog(this, res.getString("DSignMidlet.JarChooser.button"));
    if (rtnValue == JFileChooser.APPROVE_OPTION) {
        File chosenFile = chooser.getSelectedFile();
        CurrentDirectory.updateForFile(chosenFile);
        jtfJar.setText(chosenFile.toString());
        jtfJar.setCaretPosition(0);
    }
}

From source file:org.ohdsi.whiteRabbit.WhiteRabbitMain.java

private void pickTables() {
    DbSettings sourceDbSettings = getSourceDbSettings();
    if (sourceDbSettings != null) {
        if (sourceDbSettings.dataType == DbSettings.CSVFILES) {
            JFileChooser fileChooser = new JFileChooser(new File(folderField.getText()));
            fileChooser.setMultiSelectionEnabled(true);
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Delimited text files", "csv", "txt");
            fileChooser.setFileFilter(filter);

            int returnVal = fileChooser.showDialog(frame, "Select tables");
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                for (File table : fileChooser.getSelectedFiles()) {
                    String tableName = DirectoryUtilities.getRelativePath(new File(folderField.getText()),
                            table);//from   w  w w. j  a v  a2s  . co m
                    if (!tables.contains(tableName))
                        tables.add(tableName);
                    tableList.setListData(tables);
                }

            }
        } else if (sourceDbSettings.dataType == DbSettings.DATABASE) {
            RichConnection connection = new RichConnection(sourceDbSettings.server, sourceDbSettings.domain,
                    sourceDbSettings.user, sourceDbSettings.password, sourceDbSettings.dbType);
            String tableNames = StringUtilities.join(connection.getTableNames(sourceDbSettings.database), "\t");
            if (tableNames.length() == 0) {
                JOptionPane.showMessageDialog(frame, "No tables found in database " + sourceDbSettings.database,
                        "Error fetching table names", JOptionPane.ERROR_MESSAGE);
            } else {
                DBTableSelectionDialog selectionDialog = new DBTableSelectionDialog(frame, true, tableNames);
                if (selectionDialog.getAnswer()) {
                    for (Object item : selectionDialog.getSelectedItems()) {
                        if (!tables.contains(item))
                            tables.add((String) item);
                        tableList.setListData(tables);
                    }
                }
            }
            connection.close();
        }
    }
}

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

public void init() {
    backingGraph = null;/*  ww  w. j  av a  2s .co 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.photovault.swingui.BrowserWindow.java

/** 
Shows an file selection dialog that allows user to select a
file to import. After that shows the PhotoInfo dialog to allow the
user to edit the eriginal information about the file. 
*///from   w ww  . jav  a 2  s  . c  o  m

protected void importFile() {
    // Show the file chooser dialog
    JFileChooser fc = new JFileChooser();
    fc.addChoosableFileFilter(new ImageFilter());
    fc.setAccessory(new ImagePreview(fc));
    fc.setMultiSelectionEnabled(true);

    int retval = fc.showDialog(window, "Import");
    if (retval == JFileChooser.APPROVE_OPTION) {
        // Add the selected file to the database and allow user to edit its attributes
        final File[] files = fc.getSelectedFiles();

        final ProgressDlg pdlg = new ProgressDlg(window, true);

        // Add all the selected files to DB
        final PhotoInfo[] photos = new PhotoInfo[files.length];
        Thread importThread = new Thread() {
            @Override
            public void run() {

                for (int n = 0; n < files.length; n++) {
                    try {
                        photos[n] = PhotoInfo.addToDB(files[n]);
                        pdlg.setProgressPercent((n * 100) / files.length);
                        pdlg.setStatus("" + (n + 1) + " of " + files.length + " files imported.");
                    } catch (Exception e) {
                        log.error("Unexpected exception: " + e.getMessage());
                    }
                }
                pdlg.completed();
            }
        };

        importThread.start();
        pdlg.setVisible(true);

        // Show editor dialog for the added photos
        // PhotoInfoDlg dlg = new PhotoInfoDlg( window, false, photos );
        PhotoInfoDlg dlg = null;
        dlg.showDialog();
    }
}

From source file:org.p_vcd.ui.VcdDialog.java

private void selectFileButton() {
    JFileChooser fc = new JFileChooser();
    fc.setMultiSelectionEnabled(false);
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setFileFilter(/*  ww  w .  ja va 2 s.  c  om*/
            new FileNameExtensionFilter("images and videos", Parameters.get().getImageAndVideoExtensions()));
    File def = Parameters.get().getDefaultDir_QuerySelection();
    if (def != null)
        fc.setCurrentDirectory(def);
    int returnVal = fc.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        Parameters.get().updateDefaultDir_QuerySelection(fc.getCurrentDirectory());
        queryFile = fc.getSelectedFile();
        lbl_queryFile.setText(queryFile.getAbsolutePath());
        radio_queryFile.setSelected(true);
    }
}

From source file:org.sleuthkit.autopsy.modules.hashdatabase.HashDbManager.java

private String searchForFile() {
    String filePath = null;//  ww w.java  2s  . c  o  m
    JFileChooser fc = new JFileChooser();
    fc.setDragEnabled(false);
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    String[] EXTENSION = new String[] { "txt", "idx", "hash", "Hash", "kdb" }; //NON-NLS
    FileNameExtensionFilter filter = new FileNameExtensionFilter(
            NbBundle.getMessage(this.getClass(), "HashDbManager.fileNameExtensionFilter.title"), EXTENSION);
    fc.setFileFilter(filter);
    fc.setMultiSelectionEnabled(false);
    if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        File f = fc.getSelectedFile();
        try {
            filePath = f.getCanonicalPath();
        } catch (IOException ex) {
            Logger.getLogger(HashDbManager.class.getName()).log(Level.WARNING,
                    "Couldn't get selected file path", ex); //NON-NLS
        }
    }
    return filePath;
}

From source file:org.thelq.stackexchange.dbimport.gui.GUI.java

public GUI(Controller passedController) {
    //Initialize logger
    logAppender = new GUILogAppender(this);

    //Set our Look&Feel
    try {//from  w  w  w.jav  a 2  s . c  o m
        if (SystemUtils.IS_OS_WINDOWS)
            UIManager.setLookAndFeel(new WindowsLookAndFeel());
        else
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        log.warn("Defaulting to Swing L&F due to exception", e);
    }

    this.controller = passedController;
    frame = new JFrame();
    frame.setTitle("Unified StackExchange Data Dump Importer v" + Controller.VERSION);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    //Setup menu
    JMenuBar menuBar = new JMenuBar();
    menuAdd = new JMenuItem("Add Folders/Archives");
    menuAdd.setMnemonic(KeyEvent.VK_F);
    menuBar.add(menuAdd);
    frame.setJMenuBar(menuBar);

    //Primary panel
    FormLayout primaryLayout = new FormLayout("5dlu, pref:grow, 5dlu, 5dlu, pref",
            "pref, top:pref, pref, fill:140dlu:grow, pref, fill:80dlu");
    PanelBuilder primaryBuilder = new PanelBuilder(primaryLayout)
            .border(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    //DB Config panel
    primaryBuilder.addSeparator("Database Configuration", CC.xyw(1, 1, 2));
    FormLayout configLayout = new FormLayout("pref, 3dlu, pref:grow, 6dlu, pref",
            "pref, pref:grow, 3dlu, pref:grow, 3dlu, pref:grow, 3dlu, pref:grow, 3dlu, pref:grow, 3dlu, pref:grow");
    configLayout.setHonorsVisibility(true);
    final PanelBuilder configBuilder = new PanelBuilder(configLayout);
    configBuilder.addLabel("Server", CC.xy(1, 2), dbType = new JComboBox<DatabaseOption>(), CC.xy(3, 2));
    configBuilder.add(dbAdvanced = new JCheckBox("Show advanced options"), CC.xy(5, 2));
    configBuilder.addLabel("JDBC Connection", CC.xy(1, 4), jdbcString = new JTextField(15), CC.xyw(3, 4, 3));
    configBuilder.addLabel("Username", CC.xy(1, 6), username = new JTextField(10), CC.xy(3, 6));
    configBuilder.addLabel("Password", CC.xy(1, 8), password = new JPasswordField(10), CC.xy(3, 8));
    configBuilder.add(importButton = new JButton("Import"), CC.xywh(5, 6, 1, 3));
    //Add hidden
    JLabel dialectLabel = new JLabel("Dialect");
    dialectLabel.setVisible(false);
    configBuilder.add(dialectLabel, CC.xy(1, 10), dialect = new JTextField(10), CC.xyw(3, 10, 3));
    dialect.setVisible(false);
    JLabel driverLabel = new JLabel("Driver");
    driverLabel.setVisible(false);
    configBuilder.add(driverLabel, CC.xy(1, 12), driver = new JTextField(10) {
        @Override
        public void setText(String text) {
            if (StringUtils.isBlank(text))
                log.debug("Text is blank", new RuntimeException("Text " + text + " is blank"));
            super.setText(text);
        }
    }, CC.xyw(3, 12, 3));
    driver.setVisible(false);
    primaryBuilder.add(configBuilder.getPanel(), CC.xy(2, 2));

    //Options
    primaryBuilder.addSeparator("Options", CC.xyw(4, 1, 2));
    FormLayout optionsLayout = new FormLayout("pref, 3dlu, pref:grow", "");
    DefaultFormBuilder optionsBuilder = new DefaultFormBuilder(optionsLayout);
    optionsBuilder.append(disableCreateTables = new JCheckBox("Disable Creating Tables"), 3);
    optionsBuilder.append("Global Table Prefix", globalTablePrefix = new JTextField(7));
    optionsBuilder.append("Threads", threads = new JSpinner());
    //Save a core for the database
    int numThreads = Runtime.getRuntime().availableProcessors();
    numThreads = (numThreads != 1) ? numThreads - 1 : numThreads;
    threads.setModel(new SpinnerNumberModel(numThreads, 1, 100, 1));
    optionsBuilder.append("Batch Size", batchSize = new JSpinner());
    batchSize.setModel(new SpinnerNumberModel(500, 1, 500000, 1));
    primaryBuilder.add(optionsBuilder.getPanel(), CC.xy(5, 2));

    //Locations
    primaryBuilder.addSeparator("Dump Locations", CC.xyw(1, 3, 5));
    FormLayout locationsLayout = new FormLayout("pref, 15dlu, pref, 5dlu, pref, 5dlu, pref:grow, 2dlu, pref",
            "");
    locationsBuilder = new DefaultFormBuilder(locationsLayout, new ScrollablePanel()).background(Color.WHITE)
            .lineGapSize(Sizes.ZERO);
    locationsPane = new JScrollPane(locationsBuilder.getPanel());
    locationsPane.getViewport().setBackground(Color.white);
    locationsPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    locationsPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    primaryBuilder.add(locationsPane, CC.xyw(2, 4, 4));

    //Logger
    primaryBuilder.addSeparator("Log", CC.xyw(1, 5, 5));
    loggerText = new JTextPane();
    loggerText.setEditable(false);
    JPanel loggerTextPanel = new JPanel(new BorderLayout());
    loggerTextPanel.add(loggerText);
    JScrollPane loggerPane = new JScrollPane(loggerTextPanel);
    loggerPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    loggerPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    JPanel loggerPanePanel = new JPanel(new BorderLayout());
    loggerPanePanel.add(loggerPane);
    primaryBuilder.add(loggerPanePanel, CC.xyw(2, 6, 4));

    menuAdd.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //TODO: Allow 7z files but handle corner cases
            final JFileChooser fc = new JFileChooser();
            fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            fc.setMultiSelectionEnabled(true);
            fc.setDialogTitle("Select Folders/Archives");
            fc.addChoosableFileFilter(new FileNameExtensionFilter("Archives", "7z", "zip"));
            fc.addChoosableFileFilter(new FileFilter() {
                @Getter
                protected String description = "Folders";

                @Override
                public boolean accept(File file) {
                    return file.isDirectory();
                }
            });

            if (fc.showOpenDialog(frame) != JFileChooser.APPROVE_OPTION)
                return;

            //Add files and folders in a seperate thread while updating gui in EDT
            importButton.setEnabled(false);
            for (File curFile : fc.getSelectedFiles()) {
                DumpContainer dumpContainer = null;
                try {
                    if (curFile.isDirectory())
                        dumpContainer = new FolderDumpContainer(curFile);
                    else
                        dumpContainer = new ArchiveDumpContainer(controller, curFile);
                    controller.addDumpContainer(dumpContainer);
                } catch (Exception ex) {
                    String type = (dumpContainer != null) ? dumpContainer.getType() : "";
                    LoggerFactory.getLogger(getClass()).error("Cannot open " + type, ex);
                    String location = (dumpContainer != null) ? Utils.getLongLocation(dumpContainer) : "";
                    showErrorDialog(ex, "Cannot open " + location, curFile.getAbsolutePath());
                    continue;
                }
            }
            updateLocations();
            importButton.setEnabled(true);
        }
    });

    //Add options (Could be in a map, but this is cleaner)
    dbType.addItem(new DatabaseOption().name("MySQL 5.5.3+")
            .jdbcString("jdbc:mysql://127.0.0.1:3306/stackexchange?rewriteBatchedStatements=true")
            .dialect("org.hibernate.dialect.MySQL5Dialect").driver("com.mysql.jdbc.Driver"));
    dbType.addItem(new DatabaseOption().name("PostgreSQL 8.1")
            .jdbcString("jdbc:postgresql://127.0.0.1:5432/stackexchange")
            .dialect("org.hibernate.dialect.PostgreSQL81Dialect").driver("org.postgresql.Driver"));
    dbType.addItem(new DatabaseOption().name("PostgreSQL 8.2+")
            .jdbcString("jdbc:postgresql://127.0.0.1:5432/stackexchange")
            .dialect("org.hibernate.dialect.PostgreSQL82Dialect").driver("org.postgresql.Driver"));
    dbType.addItem(new DatabaseOption().name("SQL Server")
            .jdbcString("jbdc:jtds:mssql://127.0.0.1:1433/stackexchange")
            .dialect("org.hibernate.dialect.SQLServerDialect").driver("net.sourceforge.jtds.jdbc.Driver"));
    dbType.addItem(new DatabaseOption().name("SQL Server 2005+")
            .jdbcString("jbdc:jtds:mssql://127.0.0.1:1433/stackexchange")
            .dialect("org.hibernate.dialect.SQLServer2005Dialect").driver("net.sourceforge.jtds.jdbc.Driver"));
    dbType.addItem(new DatabaseOption().name("SQL Server 2008+")
            .jdbcString("jbdc:jtds:mssql://127.0.0.1:1433/stackexchange")
            .dialect("org.hibernate.dialect.SQLServer2008Dialect").driver("net.sourceforge.jtds.jdbc.Driver"));
    dbType.addItem(new DatabaseOption().name("H2").jdbcString("jdbc:h2:stackexchange")
            .dialect("org.hibernate.dialect.H2Dialect").driver("org.h2.Driver"));
    dbType.setSelectedItem(null);
    dbType.addItemListener(new ItemListener() {
        boolean shownMysqlWarning = false;

        public void itemStateChanged(ItemEvent e) {
            //Don't run this twice for a single select
            if (e.getStateChange() == ItemEvent.DESELECTED)
                return;

            DatabaseOption selectedOption = (DatabaseOption) dbType.getSelectedItem();
            if (selectedOption.name().startsWith("MySQL") && !shownMysqlWarning) {
                //Hide popup so you don't have to click twice on the dialog 
                dbType.setPopupVisible(false);
                JOptionPane.showMessageDialog(frame,
                        "Warning: Your server must be configured with character_set_server=utf8mb4"
                                + "\nOtherwise, data dumps that contain 4 byte UTF-8 characters will fail",
                        "MySQL Warning", JOptionPane.WARNING_MESSAGE);
                shownMysqlWarning = true;
            }

            setDbOption(selectedOption);
        }
    });

    //Show and hide advanced options with checkbox
    dbAdvanced.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            boolean selected = ((JCheckBox) e.getSource()).isSelected();
            driver.setVisible(selected);
            ((JLabel) driver.getClientProperty("labeledBy")).setVisible(selected);
            dialect.setVisible(selected);
            ((JLabel) dialect.getClientProperty("labeledBy")).setVisible(selected);
        }
    });

    importButton.addActionListener(new ActionListener() {
        protected void showImportError(String error) {
            JOptionPane.showMessageDialog(frame, error, "Configuration Error", JOptionPane.ERROR_MESSAGE);
        }

        protected void showInputErrorDatabase(String error) {
            if (dbType.getSelectedItem() == null)
                showImportError("No dbType specified, " + StringUtils.uncapitalize(error));
            else
                showImportError(error);
        }

        public void actionPerformed(ActionEvent e) {
            boolean validationPassed = false;
            if (controller.getDumpContainers().isEmpty())
                showImportError("Please add dump folders/archives");
            else if (StringUtils.isBlank(jdbcString.getText()))
                showInputErrorDatabase("Must specify JDBC String");
            else if (StringUtils.isBlank(driver.getText()))
                showInputErrorDatabase("Must specify driver");
            else if (StringUtils.isBlank(dialect.getText()))
                showInputErrorDatabase("Must specify hibernate dialect");
            else
                validationPassed = true;

            if (!validationPassed)
                return;

            //Disable all GUI components so they can't change anything during processing
            setGuiEnabled(false);

            //Run in new thread
            controller.getGeneralThreadPool().execute(new Runnable() {
                public void run() {
                    try {
                        start();
                    } catch (final Exception e) {
                        //Show an error message box
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                LoggerFactory.getLogger(getClass()).error("Cannot import", e);
                                showErrorDialog(e, "Cannot import", null);
                            }
                        });
                    }
                    //Renable GUI
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            setGuiEnabled(true);
                        }
                    });
                }
            });
        }
    });

    //Done, init logger
    logAppender.init();
    log.info("Finished creating GUI");

    //Display
    frame.setContentPane(primaryBuilder.getPanel());
    frame.pack();
    frame.setMinimumSize(frame.getSize());

    frame.setVisible(true);
}

From source file:org.tmpotter.ui.ActionHandler.java

/**
 * Save project as specified filename.//from   ww  w .j  av a2 s. c  o m
 */
private void saveProjectAs() {
    File outFile = new File(modelMediator.getProjectName().concat(".tmpx"));
    try {
        boolean save = false;
        boolean cancel = false;
        while (!save && !cancel) {
            final JFileChooser fc = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("TMX File", "tmpx");
            fc.setFileFilter(filter);
            boolean nameOfUser = false;
            while (!nameOfUser) {
                fc.setLocation(230, 300);
                fc.setCurrentDirectory(RuntimePreferences.getUserHome());
                fc.setDialogTitle(getString("DLG.SAVEAS"));
                fc.setMultiSelectionEnabled(false);
                fc.setSelectedFile(outFile);
                fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
                RuntimePreferences.setUserHome(fc.getCurrentDirectory());
                int returnVal;
                returnVal = fc.showSaveDialog(parent);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    outFile = fc.getSelectedFile();
                    if (!outFile.getName().endsWith(".tmpx")) {
                        outFile = new File(outFile.getName().concat(".tmpx"));
                    }
                    nameOfUser = true;
                } else {
                    nameOfUser = true;
                    cancel = true;
                }
            }
            int selected;
            if (nameOfUser && !cancel) {
                if (outFile.exists()) {
                    final Object[] options = { getString("BTN.SAVE"), getString("BTN.CANCEL") };
                    selected = JOptionPane.showOptionDialog(parent, getString("MSG.FILE_EXISTS"),
                            getString("MSG.WARNING"), JOptionPane.OK_CANCEL_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                    if (selected == 0) {
                        save = true;
                    }
                } else {
                    save = true;
                }
            }
        }
        if (save) {
            cleanTmData();
            ProjectProperties prop = modelMediator.getProjectProperties();
            prop.setFilePathProject(outFile);
            TmxpWriter.writeTmxp(prop, tmData.getDocumentOriginal(), tmData.getDocumentTranslation());
        }
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(parent, JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.tmpotter.ui.ActionHandler.java

/**
 * Action entry points.//from   www  .  j  a va 2s.c  om
 * <p>
 * All action entry points named with +ActionPerformed().
 */
public void onFileOpen() {
    final JFileChooser fc = new JFileChooser();
    File filePath = RuntimePreferences.getUserHome();
    fc.setCurrentDirectory(filePath);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Project File(.tmpx)", "tmpx");
    fc.setFileFilter(filter);
    fc.setMultiSelectionEnabled(false);
    final int returnVal = fc.showOpenDialog(parent);
    filePath = fc.getCurrentDirectory();
    RuntimePreferences.setUserHome(filePath);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        filePath = fc.getSelectedFile();

        if (filePath.getName().endsWith(".tmpx") && filePath.exists()) {
            try {
                final FileInputStream fr = new FileInputStream(filePath);
                fr.close();
                onOpenFile(filePath);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(parent, getString("MSG.ERROR.FILE_NOTFOUND"),
                        getString("MSG.ERROR"), JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(parent, getString("MSG.ERROR.FILE_NOTFOUND"), getString("MSG.ERROR"),
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}