Example usage for javax.swing JOptionPane showConfirmDialog

List of usage examples for javax.swing JOptionPane showConfirmDialog

Introduction

In this page you can find the example usage for javax.swing JOptionPane showConfirmDialog.

Prototype

public static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType)
        throws HeadlessException 

Source Link

Document

Brings up a dialog where the number of choices is determined by the optionType parameter.

Usage

From source file:com.peter.javaautoupdater.JavaAutoUpdater.java

public static void run(String ftpHost, int ftpPort, String ftpUsername, String ftpPassword,
        boolean isLocalPassiveMode, boolean isRemotePassiveMode, String basePath, String softwareName,
        String args[]) {/*  w w w.j  a  va  2  s .com*/
    System.out.println("jarName=" + jarName);
    for (String arg : args) {
        if (arg.toLowerCase().trim().equals("-noautoupdate")) {
            return;
        }
    }
    JavaAutoUpdater.basePath = basePath;
    JavaAutoUpdater.softwareName = softwareName;
    JavaAutoUpdater.args = args;

    if (!jarName.endsWith(".jar") || jarName.startsWith("JavaAutoUpdater-")) {
        if (isDebug) {
            jarName = "test.jar";
        } else {
            return;
        }
    }
    JProgressBarDialog d = new JProgressBarDialog(new JFrame(), "Auto updater", true);

    d.progressBar.setIndeterminate(true);
    d.progressBar.setStringPainted(true);
    d.progressBar.setString("Updating");
    //      d.addCancelEventListener(this);
    Thread longRunningThread = new Thread() {
        public void run() {
            d.progressBar.setString("checking latest version");
            System.out.println("checking latest version");

            FTPClient ftp = new FTPClient();
            try {
                ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
                ftp.connect(ftpHost, ftpPort);
                int reply = ftp.getReplyCode();
                System.out.println("reply=" + reply + ", " + FTPReply.isPositiveCompletion(reply));
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    JOptionPane.showMessageDialog(null, "FTP server refused connection", "error",
                            JOptionPane.ERROR_MESSAGE);
                }
                d.progressBar.setString("connected to ftp");
                System.out.println("connected to ftp");
                boolean success = ftp.login(ftpUsername, ftpPassword);
                if (!success) {
                    ftp.disconnect();
                    JOptionPane.showMessageDialog(null, "FTP login fail, can't update software", "error",
                            JOptionPane.ERROR_MESSAGE);
                }
                if (isLocalPassiveMode) {
                    ftp.enterLocalPassiveMode();
                }
                if (isRemotePassiveMode) {
                    ftp.enterRemotePassiveMode();
                }
                FTPFile[] ftpFiles = ftp.listFiles(basePath, new FTPFileFilter() {
                    @Override
                    public boolean accept(FTPFile file) {
                        if (file.getName().startsWith(softwareName)) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                });
                if (ftpFiles.length > 0) {
                    FTPFile targetFile = ftpFiles[ftpFiles.length - 1];
                    System.out.println("targetFile : " + targetFile.getName() + " , " + targetFile.getSize()
                            + "!=" + new File(jarName).length());
                    if (!targetFile.getName().equals(jarName)
                            || targetFile.getSize() != new File(jarName).length()) {
                        int r = JOptionPane.showConfirmDialog(null,
                                "Confirm to update to " + targetFile.getName(), "Question",
                                JOptionPane.YES_NO_OPTION);
                        if (r == JOptionPane.YES_OPTION) {
                            //ftp.enterRemotePassiveMode();
                            d.progressBar.setString("downloading " + targetFile.getName());
                            ftp.setFileType(FTP.BINARY_FILE_TYPE);
                            ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE);

                            d.progressBar.setIndeterminate(false);
                            d.progressBar.setMaximum(100);
                            CopyStreamAdapter streamListener = new CopyStreamAdapter() {

                                @Override
                                public void bytesTransferred(long totalBytesTransferred, int bytesTransferred,
                                        long streamSize) {
                                    int percent = (int) (totalBytesTransferred * 100 / targetFile.getSize());
                                    d.progressBar.setValue(percent);
                                }
                            };
                            ftp.setCopyStreamListener(streamListener);
                            try (FileOutputStream fos = new FileOutputStream(targetFile.getName())) {
                                ftp.retrieveFile(basePath + "/" + targetFile.getName(), fos);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            d.progressBar.setString("restarting " + targetFile.getName());
                            restartApplication(targetFile.getName());
                        }
                    }

                }
                ftp.logout();
                ftp.disconnect();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };
    d.thread = longRunningThread;
    d.setVisible(true);
}

From source file:com.bright.json.PGS.java

public static void main(String[] args) throws FileNotFoundException {

    String fileBasename = null;/*  w w  w . j  a v  a2s  . c o  m*/

    JFileChooser chooser = new JFileChooser();
    try {
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel Spreadsheets", "xls", "xlsx");
        chooser.setFileFilter(filter);
        chooser.setCurrentDirectory(new java.io.File(System.getProperty("user.home")));
        chooser.setDialogTitle("Select the Excel file");

        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);

        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
            System.out.println("getSelectedFile() : " + chooser.getSelectedFile());

            // String fileBasename =
            // chooser.getSelectedFile().toString().substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator)+1,chooser.getSelectedFile().toString().lastIndexOf("."));
            fileBasename = chooser.getSelectedFile().toString()
                    .substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator) + 1);
            System.out.println("Base name: " + fileBasename);

        } else {
            System.out.println("No Selection ");

        }
    } catch (Exception e) {

        System.out.println(e.toString());

    }
    String fileName = chooser.getSelectedFile().toString();
    InputStream inp = new FileInputStream(fileName);
    Workbook workbook = null;
    if (fileName.toLowerCase().endsWith("xlsx")) {
        try {
            workbook = new XSSFWorkbook(inp);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else if (fileName.toLowerCase().endsWith("xls")) {
        try {
            workbook = new HSSFWorkbook(inp);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    Sheet nodeSheet = workbook.getSheet("Devices");
    Sheet interfaceSheet = workbook.getSheet("Interfaces");
    System.out.println("Read nodes sheet.");
    // Row nodeRow = nodeSheet.getRow(1);
    // System.out.println(row.getCell(0).toString());
    // System.exit(0);

    JTextField uiHost = new JTextField("demo.brightcomputing.com");
    // TextPrompt puiHost = new
    // TextPrompt("demo.brightcomputing.com",uiHost);
    JTextField uiUser = new JTextField("root");
    // TextPrompt puiUser = new TextPrompt("root", uiUser);
    JTextField uiPass = new JPasswordField("");
    // TextPrompt puiPass = new TextPrompt("x5deix5dei", uiPass);

    JPanel myPanel = new JPanel(new GridLayout(5, 1));
    myPanel.add(new JLabel("Bright HeadNode hostname:"));
    myPanel.add(uiHost);
    // myPanel.add(Box.createHorizontalStrut(1)); // a spacer
    myPanel.add(new JLabel("Username:"));
    myPanel.add(uiUser);
    myPanel.add(new JLabel("Password:"));
    myPanel.add(uiPass);

    int result = JOptionPane.showConfirmDialog(null, myPanel, "Please fill in all the fields.",
            JOptionPane.OK_CANCEL_OPTION);
    if (result == JOptionPane.OK_OPTION) {
        System.out.println("Input received.");

    }

    String rhost = uiHost.getText();
    String ruser = uiUser.getText();
    String rpass = uiPass.getText();

    String cmURL = "https://" + rhost + ":8081/json";
    List<Cookie> cookies = doLogin(ruser, rpass, cmURL);
    chkVersion(cmURL, cookies);

    Map<String, Long> categories = UniqueKeyMap(cmURL, "cmdevice", "getCategories", cookies);
    Map<String, Long> networks = UniqueKeyMap(cmURL, "cmnet", "getNetworks", cookies);
    Map<String, Long> partitions = UniqueKeyMap(cmURL, "cmpart", "getPartitions", cookies);
    Map<String, Long> racks = UniqueKeyMap(cmURL, "cmpart", "getRacks", cookies);
    Map<String, Long> switches = UniqueKeyMap(cmURL, "cmdevice", "getEthernetSwitches", cookies);
    // System.out.println(switches.get("switch01"));
    // System.out.println("Size of the map: "+ switches.size());
    // System.exit(0);
    cmDevice newnode = new cmDevice();
    cmDevice.deviceObject devObj = new cmDevice.deviceObject();
    cmDevice.switchObject switchObj = new cmDevice.switchObject();
    // cmDevice.netObject netObj = new cmDevice.netObject();

    List<String> emptyslist = new ArrayList<String>();

    // Row nodeRow = nodeSheet.getRow(1);
    // Row ifRow = interfaceSheet.getRow(1);
    // System.out.println(nodeRow.getCell(0).toString());
    // nodeRow.getCell(3).getStringCellValue()
    Map<String, ArrayList<cmDevice.netObject>> ifmap = new HashMap<String, ArrayList<cmDevice.netObject>>();
    // Map<String,netObject> helperMap = new HashMap<String,netObject>();
    // Iterator<Row> rows = interfaceSheet.rowIterator ();
    // while (rows. < interfaceSheet.getPhysicalNumberOfRows()) {

    // List<netObject> netList = new ArrayList<netObject>();
    for (int i = 0; i < interfaceSheet.getPhysicalNumberOfRows(); i++) {
        Row ifRow = interfaceSheet.getRow(i);
        if (ifRow.getRowNum() == 0) {
            continue; // just skip the rows if row number is 0
        }

        System.out.println("Row nr: " + ifRow.getRowNum());
        cmDevice.netObject netObj = new cmDevice.netObject();
        ArrayList<cmDevice.netObject> helperList = new ArrayList<cmDevice.netObject>();
        netObj.setBaseType("NetworkInterface");
        netObj.setCardType(ifRow.getCell(3).getStringCellValue());
        netObj.setChildType(ifRow.getCell(4).getStringCellValue());
        netObj.setDhcp((ifRow.getCell(5).getNumericCellValue() > 0.1) ? true : false);
        netObj.setIp(ifRow.getCell(7).getStringCellValue());
        // netObj.setMac(ifRow.getCell(0).toString());
        //netObj.setModified(true);
        netObj.setName(ifRow.getCell(1).getStringCellValue());
        netObj.setNetwork(networks.get(ifRow.getCell(6).getStringCellValue()));
        //netObj.setOldLocalUniqueKey(0L);
        netObj.setRevision("");
        netObj.setSpeed(ifRow.getCell(8, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
        netObj.setStartIf("ALWAYS");
        netObj.setToBeRemoved(false);
        netObj.setUniqueKey((long) ifRow.getCell(2).getNumericCellValue());
        //netObj.setAdditionalHostnames(new ArrayList<String>(Arrays.asList(ifRow.getCell(9, Row.CREATE_NULL_AS_BLANK).getStringCellValue().split("\\s*,\\s*"))));
        //netObj.setMac(ifRow.getCell(10, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
        netObj.setMode((int) ifRow.getCell(11, Row.CREATE_NULL_AS_BLANK).getNumericCellValue());
        netObj.setOptions(ifRow.getCell(12, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
        netObj.setMembers(new ArrayList<String>(Arrays
                .asList(ifRow.getCell(13, Row.CREATE_NULL_AS_BLANK).getStringCellValue().split("\\s*,\\s*"))));
        // ifmap.put(ifRow.getCell(0).getStringCellValue(), new
        // HashMap<String, cmDevice.netObject>());
        // helperMap.put(ifRow.getCell(1).getStringCellValue(), netObj) ;
        // ifmap.get(ifRow.getCell(0).getStringCellValue()).putIfAbsent(ifRow.getCell(1).getStringCellValue(),
        // netObj);
        // ifmap.put(ifRow.getCell(0).getStringCellValue(), helperMap);

        if (!ifmap.containsKey(ifRow.getCell(0).getStringCellValue())) {
            ifmap.put(ifRow.getCell(0).getStringCellValue(), new ArrayList<cmDevice.netObject>());
        }
        helperList = ifmap.get(ifRow.getCell(0).getStringCellValue());
        helperList.add(netObj);
        ifmap.put(ifRow.getCell(0).getStringCellValue(), helperList);

        continue;
    }

    for (int i = 0; i < nodeSheet.getPhysicalNumberOfRows(); i++) {
        Row nodeRow = nodeSheet.getRow(i);
        if (nodeRow.getRowNum() == 0) {
            continue; // just skip the rows if row number is 0
        }

        newnode.setService("cmdevice");
        newnode.setCall("addDevice");

        Map<String, Long> ifmap2 = new HashMap<String, Long>();
        for (cmDevice.netObject j : ifmap.get(nodeRow.getCell(0).getStringCellValue()))
            ifmap2.put(j.getName(), j.getUniqueKey());

        switchObj.setEthernetSwitch(switches.get(nodeRow.getCell(8).getStringCellValue()));
        System.out.println(nodeRow.getCell(8).getStringCellValue());
        System.out.println(switches.get(nodeRow.getCell(8).getStringCellValue()));
        switchObj.setPrt((int) nodeRow.getCell(9).getNumericCellValue());
        switchObj.setBaseType("SwitchPort");

        devObj.setBaseType("Device");
        // devObj.setCreationTime(0L);
        devObj.setCustomPingScript("");
        devObj.setCustomPingScriptArgument("");
        devObj.setCustomPowerScript("");
        devObj.setCustomPowerScriptArgument("");
        devObj.setCustomRemoteConsoleScript("");
        devObj.setCustomRemoteConsoleScriptArgument("");
        devObj.setDisksetup("");
        devObj.setBmcPowerResetDelay(0L);
        devObj.setBurning(false);
        devObj.setEthernetSwitch(switchObj);
        devObj.setExcludeListFull("");
        devObj.setExcludeListGrab("");
        devObj.setExcludeListGrabnew("");
        devObj.setExcludeListManipulateScript("");
        devObj.setExcludeListSync("");
        devObj.setExcludeListUpdate("");
        devObj.setFinalize("");
        devObj.setRack(racks.get(nodeRow.getCell(10).getStringCellValue()));
        devObj.setRackHeight((long) nodeRow.getCell(11).getNumericCellValue());
        devObj.setRackPosition((long) nodeRow.getCell(12).getNumericCellValue());
        devObj.setIndexInsideContainer(0L);
        devObj.setInitialize("");
        devObj.setInstallBootRecord(false);
        devObj.setInstallMode("");
        devObj.setIoScheduler("");
        devObj.setLastProvisioningNode(0L);
        devObj.setMac(nodeRow.getCell(6).getStringCellValue());

        devObj.setModified(true);
        devObj.setCategory(categories.get(nodeRow.getCell(1).getStringCellValue()));
        devObj.setChildType("PhysicalNode");
        //devObj.setDatanode((nodeRow.getCell(5).getNumericCellValue() > 0.1) ? true
        //      : false);
        devObj.setHostname(nodeRow.getCell(0).getStringCellValue());
        devObj.setModified(true);
        devObj.setPartition(partitions.get(nodeRow.getCell(2).getStringCellValue()));
        devObj.setUseExclusivelyFor("Category");

        devObj.setNextBootInstallMode("");
        devObj.setNotes("");
        devObj.setOldLocalUniqueKey(0L);

        devObj.setPowerControl(nodeRow.getCell(7).getStringCellValue());

        // System.out.println(ifmap.get("excelnode001").size());
        // System.out.println(ifmap.get(nodeRow.getCell(0).getStringCellValue()).get(nodeRow.getCell(3).getStringCellValue()).getUniqueKey());

        devObj.setManagementNetwork(networks.get(nodeRow.getCell(3).getStringCellValue()));

        devObj.setProvisioningNetwork(ifmap2.get(nodeRow.getCell(4).getStringCellValue()));
        devObj.setProvisioningTransport("RSYNCDAEMON");
        devObj.setPxelabel("");
        // "rack": 90194313218,
        // "rackHeight": 1,
        // "rackPosition": 4,
        devObj.setRaidconf("");
        devObj.setRevision("");

        devObj.setSoftwareImageProxy(null);
        devObj.setStartNewBurn(false);

        devObj.setTag("00000000a000");
        devObj.setToBeRemoved(false);
        // devObj.setUcsInfoConfigured(null);
        // devObj.setUniqueKey(12345L);

        devObj.setUserdefined1("");
        devObj.setUserdefined2("");

        ArrayList<Object> mylist = new ArrayList<Object>();

        ArrayList<cmDevice.netObject> mylist2 = new ArrayList<cmDevice.netObject>();
        ArrayList<Object> emptylist = new ArrayList<Object>();

        devObj.setFsexports(emptylist);
        devObj.setFsmounts(emptylist);
        devObj.setGpuSettings(emptylist);
        devObj.setFspartAssociations(emptylist);

        devObj.setPowerDistributionUnits(emptyslist);

        devObj.setRoles(emptylist);
        devObj.setServices(emptylist);
        devObj.setStaticRoutes(emptylist);

        mylist2 = ifmap.get(nodeRow.getCell(0).getStringCellValue());

        devObj.setNetworks(mylist2);
        mylist.add(devObj);
        mylist.add(1);
        newnode.setArgs(mylist);

        GsonBuilder builder = new GsonBuilder();
        builder.enableComplexMapKeySerialization();

        // Gson g = new Gson();
        Gson g = builder.create();

        String json2 = g.toJson(newnode);

        // To be used from a real console and not Eclipse

        String message = JSonRequestor.doRequest(json2, cmURL, cookies);
        continue;
    }

    JOptionPane optionPaneF = new JOptionPane("The nodes have been added!");
    JDialog myDialogF = optionPaneF.createDialog(null, "Complete:  ");
    myDialogF.setModal(false);
    myDialogF.setVisible(true);
    doLogout(cmURL, cookies);
    // System.exit(0);
}

From source file:com.tiempometa.muestradatos.JReadTags.java

private void deleteSelectedButtonActionPerformed(ActionEvent e) {
    int response = JOptionPane.showConfirmDialog(this,
            "Se borrarn los tags seleccionados.\nEsta operacin no se puede deshacer.\nContinuar?",
            "Borrar tags seleccionados", JOptionPane.WARNING_MESSAGE);
    if (response == JOptionPane.YES_OPTION) {
        int[] rows = tagReadTable.getSelectedRows();
        List<Rfid> removedItems = new ArrayList<Rfid>();
        for (int i = 0; i < rows.length; i++) {
            Rfid rfid = tagTableModel.getData().get(tagReadTable.convertRowIndexToModel(rows[i]));
            try {
                rfidDao.delete(rfid);/*  www  . j av  a2 s  .co m*/
                removedItems.add(rfid);
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        for (int i = 0; i < removedItems.size(); i++) {
            Rfid rfid = removedItems.get(i);
            tagTableModel.getData().remove(rfid);
        }
        tagTableModel.fireTableDataChanged();
    }
}

From source file:modmanager.MainWindow.java

private void selectSkyrimDirectory(boolean force) {
    skyrimDirectoryChooser.setDialogTitle("Select Skyrim folder");
    skyrimDirectoryChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

    boolean chosen = false;

    while (skyrimDirectoryChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        /**/*w ww.  ja va 2 s.co  m*/
         * Use a while loop to check for valid skyrim installation ...
         */
        if (!FileUtils.getFile(skyrimDirectoryChooser.getSelectedFile(), "TESV.exe").exists()) {
            int result = JOptionPane.showConfirmDialog(this,
                    "It seems that this directory does not contain Skyrim!\nContinue anyways?",
                    "Invalid Skyrim directory", JOptionPane.YES_NO_CANCEL_OPTION);

            if (result == JOptionPane.CANCEL_OPTION) {
                break;
            }
            if (result == JOptionPane.YES_OPTION) {
                chosen = true;
                break;
            }
        } else {
            chosen = true;
            break;
        }
    }

    if (force && !chosen) {
        System.exit(0);
    }

    modifications.setSkyrimDirectory(skyrimDirectoryChooser.getSelectedFile());
}

From source file:net.sf.jabref.external.MoveFileAction.java

@Override
public void actionPerformed(ActionEvent event) {
    int selected = editor.getSelectedRow();

    if (selected == -1) {
        return;//from w w w.  j av a 2s  .  c om
    }

    FileListEntry entry = editor.getTableModel().getEntry(selected);

    // Check if the current file exists:
    String ln = entry.link;
    boolean httpLink = ln.toLowerCase(Locale.ENGLISH).startsWith("http");
    if (httpLink) {
        // TODO: notify that this operation cannot be done on remote links
        return;
    }

    // Get an absolute path representation:
    List<String> dirs = frame.getCurrentBasePanel().getBibDatabaseContext().getFileDirectory();
    int found = -1;
    for (int i = 0; i < dirs.size(); i++) {
        if (new File(dirs.get(i)).exists()) {
            found = i;
            break;
        }
    }
    if (found < 0) {
        JOptionPane.showMessageDialog(frame, Localization.lang("File_directory_is_not_set_or_does_not_exist!"),
                MOVE_RENAME, JOptionPane.ERROR_MESSAGE);
        return;
    }
    File file = new File(ln);
    if (!file.isAbsolute()) {
        file = FileUtil.expandFilename(ln, dirs).orElse(null);
    }
    if ((file != null) && file.exists()) {
        // Ok, we found the file. Now get a new name:
        String extension = null;
        if (entry.type.isPresent()) {
            extension = "." + entry.type.get().getExtension();
        }

        File newFile = null;
        boolean repeat = true;
        while (repeat) {
            repeat = false;
            String chosenFile;
            if (toFileDir) {
                // Determine which name to suggest:
                String suggName = FileUtil
                        .createFileNameFromPattern(eEditor.getDatabase(), eEditor.getEntry(),
                                Globals.journalAbbreviationLoader, Globals.prefs)
                        .concat(entry.type.isPresent() ? "." + entry.type.get().getExtension() : "");
                CheckBoxMessage cbm = new CheckBoxMessage(Localization.lang("Move file to file directory?"),
                        Localization.lang("Rename to '%0'", suggName),
                        Globals.prefs.getBoolean(JabRefPreferences.RENAME_ON_MOVE_FILE_TO_FILE_DIR));
                int answer;
                // Only ask about renaming file if the file doesn't have the proper name already:
                if (suggName.equals(file.getName())) {
                    answer = JOptionPane.showConfirmDialog(frame,
                            Localization.lang("Move file to file directory?"), MOVE_RENAME,
                            JOptionPane.YES_NO_OPTION);
                } else {
                    answer = JOptionPane.showConfirmDialog(frame, cbm, MOVE_RENAME, JOptionPane.YES_NO_OPTION);
                }
                if (answer != JOptionPane.YES_OPTION) {
                    return;
                }
                Globals.prefs.putBoolean(JabRefPreferences.RENAME_ON_MOVE_FILE_TO_FILE_DIR, cbm.isSelected());
                StringBuilder sb = new StringBuilder(dirs.get(found));
                if (!dirs.get(found).endsWith(File.separator)) {
                    sb.append(File.separator);
                }
                if (cbm.isSelected()) {
                    // Rename:
                    sb.append(suggName);
                } else {
                    // Do not rename:
                    sb.append(file.getName());
                }
                chosenFile = sb.toString();
            } else {
                chosenFile = FileDialogs.getNewFile(frame, file, Collections.singletonList(extension),
                        JFileChooser.SAVE_DIALOG, false);
            }
            if (chosenFile == null) {
                return; // canceled
            }
            newFile = new File(chosenFile);
            // Check if the file already exists:
            if (newFile.exists() && (JOptionPane.showConfirmDialog(frame,
                    Localization.lang("'%0' exists. Overwrite file?", newFile.getName()), MOVE_RENAME,
                    JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION)) {
                if (toFileDir) {
                    return;
                } else {
                    repeat = true;
                }
            }
        }

        if (!newFile.equals(file)) {
            try {
                boolean success = file.renameTo(newFile);
                if (!success) {
                    success = FileUtil.copyFile(file, newFile, true);
                }
                if (success) {
                    // Remove the original file:
                    if (!file.delete()) {
                        LOGGER.info("Cannot delete original file");
                    }
                    // Relativise path, if possible.
                    String canPath = new File(dirs.get(found)).getCanonicalPath();
                    if (newFile.getCanonicalPath().startsWith(canPath)) {
                        if ((newFile.getCanonicalPath().length() > canPath.length()) && (newFile
                                .getCanonicalPath().charAt(canPath.length()) == File.separatorChar)) {

                            String newLink = newFile.getCanonicalPath().substring(1 + canPath.length());
                            editor.getTableModel().setEntry(selected,
                                    new FileListEntry(entry.description, newLink, entry.type));
                        } else {
                            String newLink = newFile.getCanonicalPath().substring(canPath.length());
                            editor.getTableModel().setEntry(selected,
                                    new FileListEntry(entry.description, newLink, entry.type));
                        }

                    } else {
                        String newLink = newFile.getCanonicalPath();
                        editor.getTableModel().setEntry(selected,
                                new FileListEntry(entry.description, newLink, entry.type));
                    }
                    eEditor.updateField(editor);
                    //JOptionPane.showMessageDialog(frame, Globals.lang("File moved"),
                    //        Globals.lang("Move/Rename file"), JOptionPane.INFORMATION_MESSAGE);
                    frame.output(Localization.lang("File moved"));
                } else {
                    JOptionPane.showMessageDialog(frame, Localization.lang("Move file failed"), MOVE_RENAME,
                            JOptionPane.ERROR_MESSAGE);
                }

            } catch (SecurityException | IOException ex) {
                LOGGER.warn("Could not move file", ex);
                JOptionPane.showMessageDialog(frame,
                        Localization.lang("Could not move file '%0'.", file.getAbsolutePath())
                                + ex.getMessage(),
                        MOVE_RENAME, JOptionPane.ERROR_MESSAGE);
            }

        }
    } else {
        // File doesn't exist, so we can't move it.
        JOptionPane.showMessageDialog(frame, Localization.lang("Could not find file '%0'.", entry.link),
                Localization.lang("File not found"), JOptionPane.ERROR_MESSAGE);
    }

}

From source file:eu.ggnet.dwoss.redtape.action.StateTransitionAction.java

@Override
public void actionPerformed(ActionEvent e) {
    //TODO: All the extra checks for hints don't feel like the optimum

    //Invoice//www.  j a v  a 2 s.c om
    if (((RedTapeStateTransition) transition).getHints()
            .contains(RedTapeStateTransition.Hint.CREATES_INVOICE)) {
        int confirmInvoice = JOptionPane.showOptionDialog(parent,
                "Eine Rechnung wird unwiederruflich erstellt. Mchten Sie fortfahren?", "Rechnungserstellung",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);
        if (confirmInvoice == JOptionPane.CANCEL_OPTION)
            return;
    }

    //Cancel
    if (((RedTapeStateTransition) transition).equals(RedTapeStateTransitions.CANCEL)) {
        int confirmInvoice = JOptionPane.showOptionDialog(parent,
                "Der Vorgang wird storniert.\nMchten Sie fortfahren?", "Abbrechen des Vorganges",
                JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);
        if (confirmInvoice == JOptionPane.NO_OPTION)
            return;
    }

    if (((RedTapeStateTransition) transition).getHints()
            .contains(RedTapeStateTransition.Hint.ADDS_SETTLEMENT)) {
        SettlementViewCask view = new SettlementViewCask();
        OkCancelDialog<SettlementViewCask> dialog = new OkCancelDialog<>(parent, "Zahlung hinterlegen", view);
        dialog.setVisible(true);
        if (dialog.getCloseType() == CloseType.OK) {
            for (Document.Settlement settlement : view.getSettlements()) {
                cdoc.getDocument().add(settlement);
            }
        } else {
            return;
        }
    }
    if (((RedTapeStateTransition) transition).getHints()
            .contains(RedTapeStateTransition.Hint.UNIT_LEAVES_STOCK)) {
        for (Position p : cdoc.getDocument().getPositions(PositionType.PRODUCT_BATCH).values()) {
            //TODO not the best but fastest solution for now, this must be changed later
            if (StringUtils.isBlank(p.getRefurbishedId())) {
                if (JOptionPane.showConfirmDialog(parent,
                        "Der Vorgang enthlt Neuware, wurden alle Seriennummern erfasst?",
                        "Bitte verifizieren", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.CANCEL_OPTION)
                    return;
            }
        }
    }
    Dossier d = lookup(RedTapeWorker.class).stateChange(cdoc, transition, lookup(Guardian.class).getUsername())
            .getDossier();
    controller.reloadSelectionOnStateChange(d);
}

From source file:VoteDialog.java

private JPanel createSimpleDialogBox() {
    final int numButtons = 4;
    JRadioButton[] radioButtons = new JRadioButton[numButtons];

    final ButtonGroup group = new ButtonGroup();

    JButton voteButton = null;/*  w w  w.  ja va 2 s. c  o m*/

    final String defaultMessageCommand = "default";
    final String yesNoCommand = "yesno";
    final String yeahNahCommand = "yeahnah";
    final String yncCommand = "ync";

    radioButtons[0] = new JRadioButton("<html>Candidate 1: <font color=red>Sparky the Dog</font></html>");
    radioButtons[0].setActionCommand(defaultMessageCommand);

    radioButtons[1] = new JRadioButton("<html>Candidate 2: <font color=green>Shady Sadie</font></html>");
    radioButtons[1].setActionCommand(yesNoCommand);

    radioButtons[2] = new JRadioButton("<html>Candidate 3: <font color=blue>R.I.P. McDaniels</font></html>");
    radioButtons[2].setActionCommand(yeahNahCommand);

    radioButtons[3] = new JRadioButton(
            "<html>Candidate 4: <font color=maroon>Duke the Java<font size=-2><sup>TM</sup></font size> Platform Mascot</font></html>");
    radioButtons[3].setActionCommand(yncCommand);

    for (int i = 0; i < numButtons; i++) {
        group.add(radioButtons[i]);
    }
    // Select the first button by default.
    radioButtons[0].setSelected(true);

    voteButton = new JButton("Vote");

    voteButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String command = group.getSelection().getActionCommand();

            // ok dialog
            if (command == defaultMessageCommand) {
                JOptionPane.showMessageDialog(frame, "This candidate is a dog. Invalid vote.");

                // yes/no dialog
            } else if (command == yesNoCommand) {
                int n = JOptionPane.showConfirmDialog(frame,
                        "This candidate is a convicted felon. \nDo you still want to vote for her?",
                        "A Follow-up Question", JOptionPane.YES_NO_OPTION);
                if (n == JOptionPane.YES_OPTION) {
                    setLabel("OK. Keep an eye on your wallet.");
                } else if (n == JOptionPane.NO_OPTION) {
                    setLabel("Whew! Good choice.");
                } else {
                    setLabel("It is your civic duty to cast your vote.");
                }

                // yes/no (with customized wording)
            } else if (command == yeahNahCommand) {
                Object[] options = { "Yes, please", "No, thanks" };
                int n = JOptionPane.showOptionDialog(frame,
                        "This candidate is deceased. \nDo you still want to vote for him?",
                        "A Follow-up Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                        options, options[0]);
                if (n == JOptionPane.YES_OPTION) {
                    setLabel("I hope you don't expect much from your candidate.");
                } else if (n == JOptionPane.NO_OPTION) {
                    setLabel("Whew! Good choice.");
                } else {
                    setLabel("It is your civic duty to cast your vote.");
                }

                // yes/no/cancel (with customized wording)
            } else if (command == yncCommand) {
                Object[] options = { "Yes!", "No, I'll pass", "Well, if I must" };
                int n = JOptionPane.showOptionDialog(frame,
                        "Duke is a cartoon mascot. \nDo you  " + "still want to cast your vote?",
                        "A Follow-up Question", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
                        null, options, options[2]);
                if (n == JOptionPane.YES_OPTION) {
                    setLabel("Excellent choice.");
                } else if (n == JOptionPane.NO_OPTION) {
                    setLabel("Whatever you say. It's your vote.");
                } else if (n == JOptionPane.CANCEL_OPTION) {
                    setLabel("Well, I'm certainly not going to make you vote.");
                } else {
                    setLabel("It is your civic duty to cast your vote.");
                }
            }
            return;
        }
    });
    System.out.println("calling createPane");
    return createPane(simpleDialogDesc + ":", radioButtons, voteButton);
}

From source file:fr.insalyon.creatis.vip.vipcoworkapplet.Cowork.java

/** Initializes the applet Main */
@Override/*from   ww  w.  jav a2 s  .c om*/
public void init() {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        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(Cowork.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Cowork.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Cowork.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Cowork.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    }
    //</editor-fold>

    /* Create and display the applet */
    try {
        java.awt.EventQueue.invokeAndWait(new Runnable() {

            public void run() {
                try {
                    sessionId = getParameter("sessionId");
                    email = getParameter("email");
                    endpoint = getCodeBase().toString() + "/fr.insalyon.creatis.vip.portal.Main/coworkservice";

                    DesignFrame frame = new DesignFrame(true);
                    frame.setAppletParams(endpoint, email, sessionId);

                    String home = System.getProperty("user.home");
                    File config = new File(home + File.separator + ".cowork/config");
                    PropertiesConfiguration pc = new PropertiesConfiguration(config);

                    String password = (String) pc.getProperty("password"),
                            login = (String) pc.getProperty("login");
                    PasswordDialog p = new PasswordDialog(null, "Please login to the knowledge base");
                    while (password == null || login == null) {
                        if (p.showDialog()) {

                            login = p.getName();
                            password = p.getPass();
                        }
                        if (login != null && password != null) {
                            if (JOptionPane.showConfirmDialog(null, "Remember credentials (unencrypted)?",
                                    "Rememeber?", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                                pc.setProperty("password", password);
                                pc.setProperty("login", login);
                                pc.save();
                            }
                        }

                    }

                    KnowledgeBase kb = new KnowledgeBase("jdbc:mysql://" + getCodeBase().getHost() + "/cowork",
                            login, password, "http://cowork.i3s.cnrs.fr/");
                    frame.setKB(kb);
                    frame.setVisible(true);
                } catch (ConfigurationException ex) {
                    ex.printStackTrace();

                    JOptionPane.showMessageDialog(null, ExceptionUtils.getStackTrace(ex), "Error",
                            JOptionPane.ERROR_MESSAGE);
                } catch (SQLException ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null, ExceptionUtils.getStackTrace(ex), "Error",
                            JOptionPane.ERROR_MESSAGE);
                }

            }
        });
    } catch (Exception ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, ExceptionUtils.getStackTrace(ex), "Error",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:net.sf.clichart.main.ChartFrame.java

private void saveChart() {
    JFileChooser chooser = new JFileChooser(".");
    chooser.addChoosableFileFilter(new ExtensionFileFilter(".jpg", "JPEG files"));
    chooser.addChoosableFileFilter(new ExtensionFileFilter(".png", "PNG files"));

    if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        File outputFile = chooser.getSelectedFile();

        if (outputFile.exists()) {
            int result = JOptionPane.showConfirmDialog(this, "File exists - overwrite?", "File exists",
                    JOptionPane.OK_CANCEL_OPTION);
            if (result != JOptionPane.OK_OPTION) {
                return;
            }/* w ww . j  ava2 s. c o m*/
        }

        System.err.println("Saving chart to " + outputFile.getPath());
        try {
            new ChartSaver(m_chart, m_initialWidth, m_initialHeight).saveChart(outputFile);
        } catch (ChartSaverException e) {
            JOptionPane.showMessageDialog(this, "Failed to save chart: " + e.getMessage());
        }
    }
}

From source file:net.sf.keystore_explorer.gui.CreateApplicationGui.java

private void checkCaCerts(final KseFrame kseFrame) {

    File caCertificatesFile = applicationSettings.getCaCertificatesFile();

    if (caCertificatesFile.exists()) {
        return;/* w w w.  j  av  a  2 s  .  c  o  m*/
    }

    // cacerts file is not where we expected it => detect location and inform user
    final File newCaCertsFile = new File(AuthorityCertificates.getDefaultCaCertificatesLocation().toString());

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            int selected = JOptionPane.showConfirmDialog(kseFrame.getUnderlyingFrame(), MessageFormat
                    .format(res.getString("CreateApplicationGui.CaCertsFileNotFound.message"), newCaCertsFile),
                    KSE.getApplicationName(), JOptionPane.YES_NO_OPTION);

            if (selected == JOptionPane.YES_OPTION) {
                applicationSettings.setCaCertificatesFile(newCaCertsFile);
            }
        }
    });
}