Example usage for javax.swing JOptionPane OK_OPTION

List of usage examples for javax.swing JOptionPane OK_OPTION

Introduction

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

Prototype

int OK_OPTION

To view the source code for javax.swing JOptionPane OK_OPTION.

Click Source Link

Document

Return value form class method if OK is chosen.

Usage

From source file:eu.apenet.dpt.standalone.gui.XsdAdderActionListener.java

public void actionPerformed(ActionEvent e) {
    JFileChooser xsdChooser = new JFileChooser();
    xsdChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

    if (xsdChooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
        File file = xsdChooser.getSelectedFile();
        if (isXSD(file)) {
            XsdInfoQueryComponent xsdInfoQueryComponent = new XsdInfoQueryComponent(labels, file.getName());

            int result = JOptionPane.showConfirmDialog(parent, xsdInfoQueryComponent, "title",
                    JOptionPane.OK_CANCEL_OPTION);
            if (result == JOptionPane.OK_OPTION) {
                if (StringUtils.isEmpty(xsdInfoQueryComponent.getName())) {
                    errorMessage();//from   ww  w  .  j  ava 2s  . co m
                } else {
                    if (saveXsd(file, xsdInfoQueryComponent.getName(), false,
                            xsdInfoQueryComponent.getXsdVersion(), xsdInfoQueryComponent.getFileType())) {
                        JRadioButton newButton = new JRadioButton(xsdInfoQueryComponent.getName());
                        newButton.addActionListener(new XsdSelectorListener(dataPreparationToolGUI));
                        dataPreparationToolGUI.getGroupXsd().add(newButton);
                        dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().addToXsdPanel(newButton);
                        dataPreparationToolGUI.getAPEPanel().getApeTabbedPane()
                                .addToXsdPanel(Box.createRigidArea(new Dimension(0, 10)));
                        JOptionPane.showMessageDialog(parent, labels.getString("xsdSaved") + ".",
                                labels.getString("fileSaved"), JOptionPane.INFORMATION_MESSAGE, Utilities.icon);
                    } else {
                        errorMessage();
                    }
                }
            }
        } else {
            errorMessage();
        }
    }
}

From source file:net.sf.firemox.ui.MdbListener.java

/**
 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
 *///from   w  ww  .j  av  a2  s  .  co  m
public void actionPerformed(ActionEvent e) {
    if ("menu_options_tbs_more".equals(e.getActionCommand())) {
        // goto "more TBS" page
        try {
            WebBrowser.launchBrowser("http://sourceforge.net/project/showfiles.php?group_id="
                    + IdConst.PROJECT_ID + "&package_id=107882");
        } catch (Exception e1) {
            JOptionPane.showOptionDialog(MagicUIComponents.magicForm,
                    LanguageManager.getString("error") + " : " + e1.getMessage(),
                    LanguageManager.getString("web-pb"), JOptionPane.OK_OPTION, JOptionPane.INFORMATION_MESSAGE,
                    UIHelper.getIcon("wiz_update_error.gif"), null, null);
        }
        return;
    }
    if ("menu_options_tbs_update".equals(e.getActionCommand())) {
        // update the current TBS
        XmlConfiguration.main(new String[] { "-g", MToolKit.tbsName });
        return;
    }
    if ("menu_options_tbs_rebuild".equals(e.getActionCommand())) {
        /*
         * rebuild completely the current TBS
         */
        XmlConfiguration.main(new String[] { "-f", "-g", MToolKit.tbsName });
        return;
    }

    // We change the TBS

    // Wait for confirmation
    if (JOptionPane.YES_OPTION == JOptionPane.showOptionDialog(MagicUIComponents.magicForm,
            LanguageManager.getString("warn-disconnect"), LanguageManager.getString("disconnect"),
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, UIHelper.getIcon("wiz_update.gif"), null,
            null)) {

        // Save the current settings before changing TBS
        Magic.saveSettings();

        // Copy this settings file to the profile directory of this TBS
        final File propertyFile = MToolKit.getFile(IdConst.FILE_SETTINGS);
        try {
            FileUtils.copyFile(propertyFile, MToolKit.getTbsFile(IdConst.FILE_SETTINGS_SAVED, false));

            // Delete the current settings file of old TBS
            propertyFile.delete();

            // Load the one of the new TBS
            abstractMainForm.setMdb(e.getActionCommand());
            Configuration.loadTemplateFile(
                    MToolKit.getTbsFile(IdConst.FILE_SETTINGS_SAVED, false).getAbsolutePath());

            // Copy the saved configuration of new TBS
            FileUtils.copyFile(MToolKit.getTbsFile(IdConst.FILE_SETTINGS_SAVED, false), propertyFile);
            Log.info("Successful TBS swith to " + MToolKit.tbsName);

            // Restart the game
            System.exit(IdConst.EXIT_CODE_RESTART);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

From source file:com.gs.obevo.util.inputreader.DialogInputReader.java

@Override
public String readPassword(String promptMessage) {
    final JPasswordField jpf = new JPasswordField();
    JOptionPane jop = new JOptionPane(jpf, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
    JDialog dialog = jop.createDialog(promptMessage);
    dialog.addComponentListener(new ComponentAdapter() {
        @Override//w ww .  ja va 2  s  .  co m
        public void componentShown(ComponentEvent e) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    jpf.requestFocusInWindow();
                }
            });
        }
    });
    dialog.setVisible(true);
    int result = (Integer) jop.getValue();
    dialog.dispose();
    String password = null;
    if (result == JOptionPane.OK_OPTION) {
        password = new String(jpf.getPassword());
    }
    if (StringUtils.isEmpty(password)) {
        return null;
    } else {
        return password;
    }
}

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

public static void main(String[] args) {
    String fileBasename = null;//from   w w w. j a va  2s.c  om
    String[] zipArgs = null;
    JFileChooser chooser = new JFileChooser("/Users/panos/STR_GRID");
    try {

        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle("Select the input directory");

        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_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);

            zipArgs = new String[] { chooser.getSelectedFile().toString(),
                    chooser.getCurrentDirectory().toString() + File.separator + fileBasename + ".zip" };
            com.bright.utils.ZipFile.main(zipArgs);

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

        }
    } catch (Exception e) {

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

    }

    JTextField uiHost = new JTextField("ucs-head.brightcomputing.com");
    // TextPrompt puiHost = new
    // TextPrompt("hadoop.brightcomputing.com",uiHost);
    JTextField uiUser = new JTextField("nexus");
    // TextPrompt puiUser = new TextPrompt("nexus", uiUser);
    JTextField uiPass = new JPasswordField("system");
    // TextPrompt puiPass = new TextPrompt("", uiPass);
    JTextField uiWdir = new JTextField("/home/nexus/pp1234");
    // TextPrompt puiWdir = new TextPrompt("/home/nexus/nexus_workdir",
    // uiWdir);
    JTextField uiOut = new JTextField("foo");
    // TextPrompt puiOut = new TextPrompt("foobar123", uiOut);

    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);
    myPanel.add(new JLabel("Working Directory:"));
    myPanel.add(uiWdir);
    // myPanel.add(Box.createHorizontalStrut(1)); // a spacer
    myPanel.add(new JLabel("Output Study Name ( -s ):"));
    myPanel.add(uiOut);

    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 rfile = uiWdir.getText();
    String rhost = uiHost.getText();
    String ruser = uiUser.getText();
    String rpass = uiPass.getText();
    String nexusOut = uiOut.getText();

    String[] myarg = new String[] { zipArgs[1], ruser + "@" + rhost + ":" + rfile, nexusOut, fileBasename };
    com.bright.utils.ScpTo.main(myarg);

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

    jobSubmit myjob = new jobSubmit();
    jobSubmit.jobObject myjobObj = new jobSubmit.jobObject();

    myjob.setService("cmjob");
    myjob.setCall("submitJob");

    myjobObj.setQueue("defq");
    myjobObj.setJobname("myNexusJob");
    myjobObj.setAccount(ruser);
    myjobObj.setRundirectory(rfile);
    myjobObj.setUsername(ruser);
    myjobObj.setGroupname("cmsupport");
    myjobObj.setPriority("1");
    myjobObj.setStdinfile(rfile + "/stdin-mpi");
    myjobObj.setStdoutfile(rfile + "/stdout-mpi");
    myjobObj.setStderrfile(rfile + "/stderr-mpi");
    myjobObj.setResourceList(Arrays.asList(""));
    myjobObj.setDependencies(Arrays.asList(""));
    myjobObj.setMailNotify(false);
    myjobObj.setMailOptions("ALL");
    myjobObj.setMaxWallClock("00:10:00");
    myjobObj.setNumberOfProcesses(1);
    myjobObj.setNumberOfNodes(1);
    myjobObj.setNodes(Arrays.asList(""));
    myjobObj.setCommandLineInterpreter("/bin/bash");
    myjobObj.setUserdefined(Arrays.asList("cd " + rfile, "date", "pwd"));
    myjobObj.setExecutable("mpirun");
    myjobObj.setArguments("-env I_MPI_FABRICS shm:tcp " + Constants.NEXUSSIM_EXEC + " -mpi -c " + rfile + "/"
            + fileBasename + "/" + fileBasename + " -s " + rfile + "/" + fileBasename + "/" + nexusOut);
    myjobObj.setModules(Arrays.asList("shared", "nexus", "intel-mpi/64"));
    myjobObj.setDebug(false);
    myjobObj.setBaseType("Job");
    myjobObj.setIsSlurm(true);
    myjobObj.setUniqueKey(0);
    myjobObj.setModified(false);
    myjobObj.setToBeRemoved(false);
    myjobObj.setChildType("SlurmJob");
    myjobObj.setJobID("Nexus test");

    // Map<String,jobSubmit.jobObject > mymap= new HashMap<String,
    // jobSubmit.jobObject>();
    // mymap.put("Slurm",myjobObj);
    ArrayList<Object> mylist = new ArrayList<Object>();
    mylist.add("slurm");
    mylist.add(myjobObj);
    myjob.setArgs(mylist);

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

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

    String json2 = g.toJson(myjob);

    // To be used from a real console and not Eclipse
    Delete.main(zipArgs[1]);
    String message = JSonRequestor.doRequest(json2, cmURL, cookies);
    @SuppressWarnings("resource")
    Scanner resInt = new Scanner(message).useDelimiter("[^0-9]+");
    int jobID = resInt.nextInt();
    System.out.println("Job ID: " + jobID);

    JOptionPane optionPane = new JOptionPane(message);
    JDialog myDialog = optionPane.createDialog(null, "CMDaemon response: ");
    myDialog.setModal(false);
    myDialog.setVisible(true);

    ArrayList<Object> mylist2 = new ArrayList<Object>();
    mylist2.add("slurm");
    String JobID = Integer.toString(jobID);
    mylist2.add(JobID);
    myjob.setArgs(mylist2);
    myjob.setService("cmjob");
    myjob.setCall("getJob");
    String json3 = g.toJson(myjob);
    System.out.println("JSON Request No. 4 " + json3);

    cmReadFile readfile = new cmReadFile();
    readfile.setService("cmmain");
    readfile.setCall("readFile");
    readfile.setUserName(ruser);

    int fileByteIdx = 1;

    readfile.setPath(rfile + "/" + fileBasename + "/" + fileBasename + ".sum@+" + fileByteIdx);
    String json4 = g.toJson(readfile);

    String monFile = JSonRequestor.doRequest(json4, cmURL, cookies).replaceAll("^\"|\"$", "");
    if (monFile.startsWith("Unable")) {
        monFile = "";
    } else {
        fileByteIdx += countLines(monFile, "\\\\n");
        System.out.println("");
    }

    StringBuffer output = new StringBuffer();
    // Get the correct Line Separator for the OS (CRLF or LF)
    String nl = System.getProperty("line.separator");
    String filename = chooser.getCurrentDirectory().toString() + File.separator + fileBasename + ".sum.txt";
    System.out.println("Local monitoring file: " + filename);

    output.append(monFile.replaceAll("\\\\n", System.getProperty("line.separator")));

    String getJobJSON = JSonRequestor.doRequest(json3, cmURL, cookies);
    jobGet getJobObj = new Gson().fromJson(getJobJSON, jobGet.class);
    System.out.println("Job " + jobID + " status: " + getJobObj.getStatus().toString());

    while (getJobObj.getStatus().toString().equals("RUNNING")
            || getJobObj.getStatus().toString().equals("COMPLETING")) {
        try {

            getJobJSON = JSonRequestor.doRequest(json3, cmURL, cookies);
            getJobObj = new Gson().fromJson(getJobJSON, jobGet.class);
            System.out.println("Job " + jobID + " status: " + getJobObj.getStatus().toString());

            readfile.setPath(rfile + "/" + fileBasename + "/" + fileBasename + ".sum@+" + fileByteIdx);
            json4 = g.toJson(readfile);
            monFile = JSonRequestor.doRequest(json4, cmURL, cookies).replaceAll("^\"|\"$", "");
            if (monFile.startsWith("Unable")) {
                monFile = "";
            } else {

                output.append(monFile.replaceAll("\\\\n", System.getProperty("line.separator")));
                System.out.println("FILE INDEX:" + fileByteIdx);
                fileByteIdx += countLines(monFile, "\\\\n");
            }
            Thread.sleep(Constants.STATUS_CHECK_INTERVAL);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }

    }

    Gson gson_nice = new GsonBuilder().setPrettyPrinting().create();
    String json_out = gson_nice.toJson(getJobJSON);
    System.out.println(json_out);
    System.out.println("JSON Request No. 5 " + json4);

    readfile.setPath(rfile + "/" + fileBasename + "/" + fileBasename + ".sum@+" + fileByteIdx);
    json4 = g.toJson(readfile);
    monFile = JSonRequestor.doRequest(json4, cmURL, cookies).replaceAll("^\"|\"$", "");
    if (monFile.startsWith("Unable")) {
        monFile = "";
    } else {

        output.append(monFile.replaceAll("\\\\n", System.getProperty("line.separator")));
        fileByteIdx += countLines(monFile, "\\\\n");
    }
    System.out.println("FILE INDEX:" + fileByteIdx);

    /*
     * System.out.print("Monitoring file: " + monFile.replaceAll("\\n",
     * System.getProperty("line.separator"))); try {
     * FileUtils.writeStringToFile( new
     * File(chooser.getCurrentDirectory().toString() + File.separator +
     * fileBasename + ".sum.txt"), monFile.replaceAll("\\n",
     * System.getProperty("line.separator"))); } catch (IOException e) {
     * 
     * e.printStackTrace(); }
     */

    if (getJobObj.getStatus().toString().equals("COMPLETED")) {
        String[] zipArgs_from = new String[] { chooser.getSelectedFile().toString(),
                chooser.getCurrentDirectory().toString() + File.separator + fileBasename + "_out.zip" };
        String[] myarg_from = new String[] {
                ruser + "@" + rhost + ":" + rfile + "/" + fileBasename + "_out.zip", zipArgs_from[1], rfile,
                fileBasename };
        com.bright.utils.ScpFrom.main(myarg_from);

        JOptionPane optionPaneS = new JOptionPane("Job execution completed without errors!");
        JDialog myDialogS = optionPaneS.createDialog(null, "Job status: ");
        myDialogS.setModal(false);
        myDialogS.setVisible(true);

    } else {
        JOptionPane optionPaneF = new JOptionPane("Job execution FAILED!");
        JDialog myDialogF = optionPaneF.createDialog(null, "Job status: ");
        myDialogF.setModal(false);
        myDialogF.setVisible(true);
    }

    try {
        System.out.println("Local monitoring file: " + filename);

        BufferedWriter out = new BufferedWriter(new FileWriter(filename));
        String outText = output.toString();
        String newString = outText.replace("\\\\n", nl);

        System.out.println("Text: " + outText);
        out.write(newString);

        out.close();
        rmDuplicateLines.main(filename);
    } catch (IOException e) {
        e.printStackTrace();
    }
    doLogout(cmURL, cookies);
    System.exit(0);
}

From source file:net.sourceforge.atunes.kernel.actions.RemoveFromDiskAction.java

@Override
public void actionPerformed(ActionEvent e) {
    // Show confirmation
    if (VisualHandler.getInstance().showConfirmationDialog(LanguageTool.getString("REMOVE_CONFIRMATION"),
            LanguageTool.getString("CONFIRMATION")) == JOptionPane.OK_OPTION) {

        // Podcast view
        if (NavigationHandler.getInstance().getCurrentView() instanceof PodcastNavigationView) {
            fromPodcastView();// w  w  w  . ja  v  a2 s.c o  m
            // Repository or device view with folder view mode, folder selected: delete folders instead of content
        } else if ((NavigationHandler.getInstance().getCurrentView() instanceof RepositoryNavigationView
                || NavigationHandler.getInstance().getCurrentView() instanceof DeviceNavigationView)
                && NavigationHandler.getInstance().getCurrentViewMode() == ViewMode.FOLDER && ControllerProxy
                        .getInstance().getNavigationController().getPopupMenuCaller() instanceof JTree) {
            fromRepositoryOrDeviceView();

        } else {
            fromOtherViews();
        }
    }
}

From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.standalone.StandaloneShutdownDialog.java

private void displayShutdownDialog() {
    String serverId = ServerDetector.getServerId();
    log.info("Running in: " + (serverId != null ? serverId : "unknown server"));
    log.info("Console: " + ((System.console() != null) ? "available" : "not available"));
    log.info("Headless: " + (GraphicsEnvironment.isHeadless() ? "yes" : "no"));

    // Show this only when run from the standalone JAR via a double-click
    if (System.console() == null && !GraphicsEnvironment.isHeadless() && ServerDetector.isWinstone()) {
        log.info("If you are running WebAnno in a server environment, please use '-Djava.awt.headless=true'");

        EventQueue.invokeLater(new Runnable() {
            @Override//from ww  w.j  a v  a 2s.  c om
            public void run() {
                final JOptionPane optionPane = new JOptionPane(new JLabel(
                        "<HTML>WebAnno is running now and can be accessed via <a href=\"http://localhost:8080\">http://localhost:8080</a>.<br>"
                                + "WebAnno works best with the browsers Google Chrome or Safari.<br>"
                                + "Use this dialog to shut WebAnno down.</HTML>"),
                        JOptionPane.INFORMATION_MESSAGE, JOptionPane.OK_OPTION, null,
                        new String[] { "Shutdown" });

                final JDialog dialog = new JDialog((JFrame) null, "WebAnno", true);
                dialog.setContentPane(optionPane);
                dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                dialog.addWindowListener(new WindowAdapter() {
                    @Override
                    public void windowClosing(WindowEvent we) {
                        // Avoid closing window by other means than button
                    }
                });
                optionPane.addPropertyChangeListener(new PropertyChangeListener() {
                    @Override
                    public void propertyChange(PropertyChangeEvent aEvt) {
                        if (dialog.isVisible() && (aEvt.getSource() == optionPane)
                                && (aEvt.getPropertyName().equals(JOptionPane.VALUE_PROPERTY))) {
                            System.exit(0);
                        }
                    }
                });
                dialog.pack();
                dialog.setVisible(true);
            }
        });
    } else {
        log.info("Running in server environment or from command line: disabling interactive shutdown dialog.");
    }
}

From source file:net.sf.maltcms.chromaui.ui.paintScales.PaintScaleDialogAction.java

/**
 *
 * @return//from ww w .ja  v a  2 s.  c  o  m
 */
public PaintScale showPaintScaleDialog() {
    if (this.psp == null) {
        this.psp = new PaintScalePanel(this.ps, this.alpha, this.beta);
    }
    int val = JOptionPane.showConfirmDialog(this.parent, psp, "Select Color Scale",
            JOptionPane.OK_CANCEL_OPTION);
    if (val == JOptionPane.OK_OPTION) {
        this.ps = psp.getPaintScale();
    }
    if (this.ps == null) {
        this.ps = psp.getDefaultPaintScale();
    }
    return this.ps;
}

From source file:gov.nih.nci.nbia.StandaloneDMV2.java

void checkCompatibility() {
    if (serverUrl.endsWith("DownloadServlet")) {
        this.serverUrl = serverUrl.concat("V2");
    }/*  w ww.jav  a2 s. c o m*/

    if (!serverUrl.endsWith("DownloadServletV2")) {
        Object[] options = { "OK" };

        int n = JOptionPane.showOptionDialog(frame, serverVersionMsg, "Incompatible Server Notification",
                JOptionPane.OK_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
        System.exit(n);
    }
}

From source file:latexstudio.editor.DbxFileActions.java

/**
 * Shows a .tex files list from user's dropbox and opens the selected one
 *
 * @return List, that contatins user's .tex files from his dropbox; can be
 * empty/*ww  w  . j  a v a  2 s.c o  m*/
 */
public void openFromDropbox(DropboxRevisionsTopComponent drtc, RevisionDisplayTopComponent revtc) {
    List<DbxEntryDto> dbxEntries = getDbxTexEntries(DbxUtil.getDbxClient());

    if (!dbxEntries.isEmpty()) {
        JList<DbxEntryDto> list = new JList(dbxEntries.toArray());
        list.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);
        int option = JOptionPane.showConfirmDialog(null, list, "Open file from Dropbox",
                JOptionPane.OK_CANCEL_OPTION);

        if (option == JOptionPane.OK_OPTION && !list.isSelectionEmpty()) {
            DbxEntryDto entry = list.getSelectedValue();
            String localPath = ApplicationUtils.getAppDirectory() + File.separator + entry.getName();
            File outputFile = DbxUtil.downloadRemoteFile(entry, localPath);

            revtc.close();

            drtc.updateRevisionsList(entry.getPath());
            drtc.open();
            drtc.requestActive();

            String content = FileService.readFromFile(outputFile.getAbsolutePath());
            etc.setEditorContent(content);
            etc.setCurrentFile(outputFile);
            etc.setDbxState(new DbxState(entry.getPath(), entry.getRevision()));
            etc.setModified(false);
            etc.setPreviewDisplayed(false);
        }
    } else {
        JOptionPane.showMessageDialog(etc, "No .tex files found!", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:hudson.lifecycle.WindowsSlaveInstaller.java

/**
 * Called when the install menu is selected
 *//*  w ww  .  j a va  2 s .c o  m*/
public void actionPerformed(ActionEvent e) {
    int r = JOptionPane.showConfirmDialog(dialog,
            "This will install a slave agent as a Windows service,\n"
                    + "so that this slave will connect to Hudson as soon as the machine boots.\n"
                    + "Do you want to proceed with installation?",
            Messages.WindowsInstallerLink_DisplayName(), JOptionPane.OK_CANCEL_OPTION);
    if (r != JOptionPane.OK_OPTION)
        return;

    if (!DotNet.isInstalled(2, 0)) {
        JOptionPane.showMessageDialog(dialog, ".NET Framework 2.0 or later is required for this feature",
                Messages.WindowsInstallerLink_DisplayName(), JOptionPane.ERROR_MESSAGE);
        return;
    }

    final File dir = new File(rootDir);

    try {
        final File slaveExe = new File(dir, "hudson-slave.exe");
        FileUtils.copyURLToFile(getClass().getResource("/windows-service/hudson.exe"), slaveExe);

        // write out the descriptor
        URL jnlp = new URL(engine.getHudsonUrl(), "computer/" + engine.slaveName + "/slave-agent.jnlp");
        String xml = generateSlaveXml(System.getProperty("java.home") + "\\bin\\java.exe",
                "-jnlpUrl " + jnlp.toExternalForm());
        FileUtils.writeStringToFile(new File(dir, "hudson-slave.xml"), xml, "UTF-8");

        // copy slave.jar
        URL slaveJar = new URL(engine.getHudsonUrl(), "jnlpJars/remoting.jar");
        File dstSlaveJar = new File(dir, "slave.jar").getCanonicalFile();
        if (!dstSlaveJar.exists()) // perhaps slave.jar is already there?
            FileUtils.copyURLToFile(slaveJar, dstSlaveJar);

        // install as a service
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        StreamTaskListener task = new StreamTaskListener(baos);
        r = new LocalLauncher(task).launch().cmds(slaveExe, "install").stdout(task).pwd(dir).join();
        if (r != 0) {
            JOptionPane.showMessageDialog(dialog, baos.toString(), "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        r = JOptionPane.showConfirmDialog(dialog,
                "Installation was successful. Would you like to\n"
                        + "Stop this slave agent and start the newly installed service?",
                Messages.WindowsInstallerLink_DisplayName(), JOptionPane.OK_CANCEL_OPTION);
        if (r != JOptionPane.OK_OPTION)
            return;

        // let the service start after we close our connection, to avoid conflicts
        Runtime.getRuntime().addShutdownHook(new Thread("service starter") {
            public void run() {
                try {
                    StreamTaskListener task = new StreamTaskListener(System.out);
                    int r = new LocalLauncher(task).launch().cmds(slaveExe, "start").stdout(task).pwd(dir)
                            .join();
                    task.getLogger()
                            .println(r == 0 ? "Successfully started" : "start service failed. Exit code=" + r);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        System.exit(0);
    } catch (Exception t) {
        StringWriter sw = new StringWriter();
        t.printStackTrace(new PrintWriter(sw));
        JOptionPane.showMessageDialog(dialog, sw.toString(), "Error", JOptionPane.ERROR_MESSAGE);
    }
}