Example usage for javax.swing JOptionPane showOptionDialog

List of usage examples for javax.swing JOptionPane showOptionDialog

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public static int showOptionDialog(Component parentComponent, Object message, String title, int optionType,
        int messageType, Icon icon, Object[] options, Object initialValue) throws HeadlessException 

Source Link

Document

Brings up a dialog with a specified icon, where the initial choice is determined by the initialValue parameter and the number of choices is determined by the optionType parameter.

Usage

From source file:be.ac.ua.comp.scarletnebula.gui.windows.LinkUnlinkWindow.java

private final JPanel getMainPanel() {
    final JPanel mainPanel = new JPanel(new GridBagLayout());
    mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
    final ServerList linkedServerList = new ServerList(linkedServerListModel);
    linkedServerList.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
    final JScrollPane linkedServerScrollPane = new JScrollPane(linkedServerList);
    linkedServerScrollPane/* ww  w.  ja va  2 s.c o m*/
            .setBorder(BorderFactory.createTitledBorder(new EmptyBorder(5, 20, 20, 20), "Linked Servers"));
    // Doesn't matter what this is set to, as long as it's the same as the
    // one for unlinkedServerScrollPane
    linkedServerScrollPane.setPreferredSize(new Dimension(10, 10));

    final GridBagConstraints c = new GridBagConstraints();

    c.fill = GridBagConstraints.BOTH;
    c.gridx = 0;
    c.gridy = 0;
    c.weightx = 0.5;
    c.weighty = 1.0;

    mainPanel.add(linkedServerScrollPane, c);

    final ServerList unlinkedServerList = new ServerList(unlinkedServerListModel);
    unlinkedServerList.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
    final JScrollPane unlinkedServerScrollPane = new JScrollPane(unlinkedServerList);
    unlinkedServerScrollPane
            .setBorder(BorderFactory.createTitledBorder(new EmptyBorder(5, 20, 20, 20), "Unlinked Servers"));

    // Doesn't matter what this is set to, as long as it's the same as the
    // one for unlinkedServerScrollPane
    unlinkedServerScrollPane.setPreferredSize(new Dimension(10, 10));

    final JPanel middlePanel = new JPanel();
    middlePanel.setLayout(new BoxLayout(middlePanel, BoxLayout.Y_AXIS));
    middlePanel.add(Box.createVerticalGlue());

    final JButton linkSelectionButton = new JButton("<");
    final JButton unlinkSelectionButton = new JButton(">");

    linkSelectionButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            // Move selection from unlinked to linked list
            final int selection = unlinkedServerList.getSelectedIndex();

            if (selection < 0) {
                return;
            }

            final Server server = unlinkedServerListModel.getVisibleServerAtIndex(selection);

            unlinkedServerListModel.removeServer(server);

            linkedServerListModel.addServer(server);
        }
    });

    unlinkSelectionButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent e) {
            // Move selection from linked to unlinked list
            final int selection = linkedServerList.getSelectedIndex();

            if (selection < 0) {
                return;
            }

            final int answer = JOptionPane.showOptionDialog(LinkUnlinkWindow.this,
                    "You are about to unlink a server. "
                            + "Unlinking a server will permanently remove \nall data associated with "
                            + "this server, but the server will keep running. "
                            + "\n\nAre you sure you wish to continue?",
                    "Unlink Server", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, null, null);

            if (answer != JOptionPane.YES_OPTION) {
                return;
            }

            final Server server = linkedServerListModel.getVisibleServerAtIndex(selection);

            linkedServerListModel.removeServer(server);

            unlinkedServerListModel.addServer(server);
        }
    });

    middlePanel.add(unlinkSelectionButton);
    middlePanel.add(Box.createVerticalStrut(10));
    middlePanel.add(linkSelectionButton);
    middlePanel.add(Box.createVerticalGlue());

    c.gridx = 1;
    c.gridy = 0;
    c.weightx = 0.0;
    c.weighty = 0.0;

    mainPanel.add(middlePanel, c);

    c.gridx = 2;
    c.gridy = 0;
    c.weightx = 0.5;
    c.weighty = 1.0;

    mainPanel.add(unlinkedServerScrollPane, c);
    return mainPanel;
}

From source file:com.funambol.email.admin.user.ResultSearchUserPanel.java

/**
 * Set up graphic elements for this panel.
 *
 * @throws Exception if error occures during creation of the panel
 *//*from  w w  w.  j  a v a  2s .co  m*/
private void init() throws Exception {

    // create objects to display
    this.setLayout(new BorderLayout());
    this.setBorder(BorderFactory.createEmptyBorder());

    // create a model for the user table and pass it to the JTable object
    model = new UserTableModel();
    table = new JTable(model);

    table.setShowGrid(true);
    table.setAutoscrolls(true);
    table.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);
    JScrollPane scrollpane = new JScrollPane(table);
    table.setPreferredScrollableViewportSize(new Dimension(800, 200));
    table.setFont(GuiFactory.defaultTableFont);
    table.getTableHeader().setFont(GuiFactory.defaultTableHeaderFont);
    this.add(scrollpane, BorderLayout.CENTER);

    //
    // Select user.
    //
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    ListSelectionModel rowSM = table.getSelectionModel();

    rowSM.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent event) {

            if (event.getValueIsAdjusting()) {
                return;
            }

            ListSelectionModel lsm = (ListSelectionModel) event.getSource();

            if (lsm.isSelectionEmpty()) {

                selectedUser = null;
            } else {

                int selectedRow = lsm.getMinSelectionIndex();
                selectedUser = users[selectedRow];
            }
        }
    });

    rowSM.clearSelection();

    table.addMouseListener(new MouseAdapter() {

        public void mouseClicked(MouseEvent event) {

            if (event.getClickCount() < 2) {
                return;
            }

            //
            // If the selected user is already associated to an account
            // then insertion process can't go on.
            //

            String userName = selectedUser.getUsername();
            String value[] = new String[] { userName };
            WhereClause wc = new WhereClause("username", value, WhereClause.OPT_EQ, true);
            MailServerAccount[] tmp = null;
            try {
                tmp = WSDao.getAccounts(wc);
            } catch (Exception e) {
            }

            if (tmp.length > 0) {

                StringBuilder sb = new StringBuilder("The user ");
                sb.append(userName).append(" is already associated to an account");
                Object[] options = { "OK" };
                JOptionPane.showOptionDialog(null, sb.toString(), "Warning", JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.WARNING_MESSAGE, null, options, options[0]);

            } else {
                //
                // Go to next step.
                //
                step.goToNextStep();
            }
        }
    });

}

From source file:com.pdk.DisassembleElfAction.java

private void showList() {
    Project project = NetbeansUtil.getPeterProject();
    File dir = new File(project.getProjectDirectory().getPath());
    Collection<File> files = FileUtils.listFiles(dir, new String[] { "o", "exe" }, true);
    if (files.isEmpty()) {
        return;/*from   w w w  . jav a 2s. c om*/
    }
    files.add(new File(dir.getAbsolutePath() + File.separator + "kernel/kernel"));
    Iterator<File> iter = files.iterator();
    while (iter.hasNext()) {
        File file = iter.next();
        String relativePath = file.getAbsolutePath().substring(dir.getAbsolutePath().length());
        if (relativePath.startsWith("/toolchain/")) {
            iter.remove();
        }
    }
    String[] arr = new String[files.size()];
    iter = files.iterator();
    int x = 0;
    while (iter.hasNext()) {
        File file = iter.next();
        String relativePath = file.getAbsolutePath().substring(dir.getAbsolutePath().length() + 1);
        arr[x] = relativePath;
        x++;
    }
    Arrays.sort(arr, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            if (o1.startsWith("kernel/")) {
                return -1;
            } else if (o1.startsWith("kernel/")) {
                return 1;
            } else {
                return o1.compareTo(o2);
            }
        }
    });

    String file = (String) JOptionPane.showInputDialog(null, null, "Please select an elf file",
            JOptionPane.QUESTION_MESSAGE, null, arr, arr[0]);
    if (file != null) {
        try {
            Object[] options = { "Disasm", "Sections", "Cancel" };
            int n = JOptionPane.showOptionDialog(null, "Please select", "Question",
                    JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]);

            if (n == 2) {
                return;
            }
            String command2 = null;
            if (n == 0) {
                command2 = "i586-peter-elf-objdump -S";
            } else if (n == 1) {
                command2 = "i586-peter-elf-readelf -S";
            }
            if (command2 == null) {
                return;
            }
            final String command = "/toolchain/bin/" + command2 + " " + file;

            process = Runtime.getRuntime().exec(command, null, dir);
            InputStreamReader isr = new InputStreamReader(process.getInputStream());
            final BufferedReader br = new BufferedReader(isr, 1024 * 1024 * 50);
            final JProgressBarDialog d = new JProgressBarDialog(new JFrame(),
                    "i586-peter-elf-objdump -S " + file, true);

            d.progressBar.setIndeterminate(true);
            d.progressBar.setStringPainted(true);
            d.progressBar.setString("Updating");
            d.addCancelEventListener(this);
            Thread longRunningThread = new Thread() {
                public void run() {
                    try {
                        lines = new StringBuilder();
                        String line;
                        stop = false;
                        while (!stop && (line = br.readLine()) != null) {
                            d.progressBar.setString(line);
                            lines.append(line).append("\n");
                        }
                        DisassembleDialog disassembleDialog = new DisassembleDialog();
                        disassembleDialog.setTitle(command);
                        if (((DefaultComboBoxModel) disassembleDialog.enhancedTextArea1.fontComboBox.getModel())
                                .getIndexOf("Monospaced") != -1) {
                            disassembleDialog.enhancedTextArea1.fontComboBox.setSelectedItem("Monospaced");
                        }
                        if (((DefaultComboBoxModel) disassembleDialog.enhancedTextArea1.fontComboBox.getModel())
                                .getIndexOf("Monospaced.plain") != -1) {
                            disassembleDialog.enhancedTextArea1.fontComboBox
                                    .setSelectedItem("Monospaced.plain");
                        }
                        disassembleDialog.enhancedTextArea1.fontComboBox.setSelectedItem("Monospaced");
                        disassembleDialog.enhancedTextArea1.setText(lines.toString());
                        disassembleDialog.setVisible(true);
                    } catch (Exception ex) {
                        ModuleLib.log(CommonLib.printException(ex));
                    }
                }
            };
            d.thread = longRunningThread;
            d.setVisible(true);
        } catch (Exception ex) {
            ModuleLib.log(CommonLib.printException(ex));
        }
    }
}

From source file:it.unibas.spicygui.controllo.mapping.ActionGenerateAndTranslate.java

private void checkForPKConstraints(MappingTask mappingTask, HashSet<String> pkTableNames, int scenarioNo)
        throws DAOException {
    if (!pkTableNames.isEmpty()) {
        NotifyDescriptor notifyDescriptor = new NotifyDescriptor.Confirmation(
                NbBundle.getMessage(Costanti.class, Costanti.MESSAGE_PK_TABLES),
                DialogDescriptor.YES_NO_OPTION);
        DialogDisplayer.getDefault().notify(notifyDescriptor);
        if (notifyDescriptor.getValue().equals(NotifyDescriptor.YES_OPTION)) {
            String[] format = { NbBundle.getMessage(Costanti.class, Costanti.OUTPUT_TYPE_CSV),
                    NbBundle.getMessage(Costanti.class, Costanti.OUTPUT_TYPE_JSON) };
            int formatResponse = JOptionPane.showOptionDialog(null,
                    NbBundle.getMessage(Costanti.class, Costanti.MESSAGE_PK_OUTPUT),
                    NbBundle.getMessage(Costanti.class, Costanti.PK_OUTPUT_TITLE), JOptionPane.DEFAULT_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, format, format[0]);
            if (formatResponse != JOptionPane.CLOSED_OPTION) {
                JFileChooser chooser = vista.getFileChooserSalvaFolder();
                File file;//from w  w  w. j  a  v a  2s . co m
                int returnVal = chooser.showDialog(WindowManager.getDefault().getMainWindow(),
                        NbBundle.getMessage(Costanti.class, Costanti.EXPORT));
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    file = chooser.getSelectedFile();
                    if (formatResponse == 0) {
                        DAOCsv daoCsv = new DAOCsv();
                        daoCsv.exportPKConstraintCSVinstances(mappingTask, pkTableNames, file.getAbsolutePath(),
                                scenarioNo);
                        DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
                                NbBundle.getMessage(Costanti.class, Costanti.EXPORT_COMPLETED_OK)));
                    } else if (formatResponse == 1) {
                        DAOJson daoJson = new DAOJson();
                        daoJson.exportPKConstraintJsoninstances(mappingTask, pkTableNames,
                                file.getAbsolutePath(), scenarioNo);
                        DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
                                NbBundle.getMessage(Costanti.class, Costanti.EXPORT_COMPLETED_OK)));
                    }
                }
            }
        }
    }
}

From source file:com.sec.ose.osi.sdk.protexsdk.discovery.report.DefaultEntityListCreator.java

protected ReportEntityList buildEntityListFromHTML(BufferedReader htmlReportReader,
        ArrayList<String> entityKeyList, ArrayList<String> duplicationCheckingField) {
    ReportEntityList reportEntityList = new ReportEntityList();
    ReportEntity reportEntity = null;//from   ww  w  .  j  a va  2s.c o m
    String tmpLine = null;

    if (duplicationCheckingField == null) {
        duplicationCheckingField = new ArrayList<String>();
    }

    int insertedCnt = 0;

    try {
        StringBuffer tmpValue = new StringBuffer("");
        while ((tmpLine = htmlReportReader.readLine()) != null) {
            tmpLine = tmpLine.trim();
            if (tmpLine.startsWith("<tr ")) {
                reportEntity = new ReportEntity();
                int index = 0;
                while ((tmpLine = htmlReportReader.readLine()) != null) {
                    tmpLine = tmpLine.trim();
                    if (tmpLine.startsWith("<td ")) {
                        while ((tmpLine = htmlReportReader.readLine()) != null) {
                            tmpLine = tmpLine.trim();
                            if (tmpLine.startsWith("</td>")) {
                                String key = entityKeyList.get(index);
                                String value = "";

                                if (key.equals(ReportInfo.COMPARE_CODE_MATCHES.COMPARE_CODE_MATCHES_LINK)) {
                                    value = extractURL(tmpValue);
                                } else {
                                    value = removeTag(tmpValue);
                                }
                                reportEntity.setValue(key, value);
                                tmpValue.setLength(0);
                                ++index;
                                break;
                            }
                            tmpValue.append(tmpLine);
                        }
                    }
                    if (tmpLine.startsWith("</tr>")) {
                        if (hasNoData(entityKeyList, index)) {
                            break;
                        }
                        reportEntityList.addEntity(reportEntity);
                        insertedCnt++;
                        if (insertedCnt % 10000 == 0) {
                            log.debug("buildEntityList insertedCnt: " + insertedCnt);
                        }
                        break;
                    }
                }
            }
            if (tmpLine.startsWith(HTML_DATA_TABLE_END_TAG)) {
                break;
            }
        }
    } catch (IOException e) {
        log.warn(e);
        String[] buttonOK = { "OK" };
        JOptionPane.showOptionDialog(null, "Out Of Memory Error", "Java heap space", JOptionPane.OK_OPTION,
                JOptionPane.ERROR_MESSAGE, null, buttonOK, "OK");
    }
    log.debug("buildEntityList insertedCnt finally : " + insertedCnt);
    return reportEntityList;
}

From source file:com.ebixio.virtmus.stats.StatsLogger.java

/**
 * Ask the user if they want to help by uploading stats logs.
 *//*from w  ww.java 2s .co  m*/
private UploadStats promptUser() {
    String yes = NbBundle.getMessage(StatsLogger.class, "BTN_Yes"),
            maybeLater = NbBundle.getMessage(StatsLogger.class, "BTN_MaybeLater"),
            never = NbBundle.getMessage(StatsLogger.class, "BTN_Never");

    Icon icon = ImageUtilities.loadImageIcon("com/ebixio/virtmus/resources/VirtMus32x32.png", false);
    int userChoice = JOptionPane.showOptionDialog(null, NbBundle.getMessage(StatsLogger.class, "MSG_Text"),
            NbBundle.getMessage(StatsLogger.class, "MSG_Title"), JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE, icon, new Object[] { yes, maybeLater, never }, yes);

    switch (userChoice) {
    case 0:
        return UploadStats.Yes;
    case 2:
        return UploadStats.No;
    case 1:
        return UploadStats.Maybe;
    case -1: // User closed the dialog. Leave it as "Unknown".
    default:
        return UploadStats.Unknown;
    }
}

From source file:net.sf.jabref.exporter.SaveDatabaseAction.java

private boolean saveDatabase(File file, boolean selectedOnly, Charset encoding) throws SaveException {
    SaveSession session;/*from  ww w .j av  a2s. c o  m*/
    frame.block();
    try {
        SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs)
                .withEncoding(encoding);
        BibDatabaseWriter databaseWriter = new BibDatabaseWriter();
        if (selectedOnly) {
            session = databaseWriter.savePartOfDatabase(panel.getBibDatabaseContext(), prefs,
                    panel.getSelectedEntries());

        } else {
            session = databaseWriter.saveDatabase(panel.getBibDatabaseContext(), prefs);

        }
        panel.registerUndoableChanges(session);

    } catch (UnsupportedCharsetException ex2) {
        JOptionPane.showMessageDialog(frame,
                Localization.lang("Could not save file.") + Localization
                        .lang("Character encoding '%0' is not supported.", encoding.displayName()),
                Localization.lang("Save database"), JOptionPane.ERROR_MESSAGE);
        throw new SaveException("rt");
    } catch (SaveException ex) {
        if (ex == SaveException.FILE_LOCKED) {
            throw ex;
        }
        if (ex.specificEntry()) {
            // Error occured during processing of
            // be. Highlight it:
            int row = panel.mainTable.findEntry(ex.getEntry());
            int topShow = Math.max(0, row - 3);
            panel.mainTable.setRowSelectionInterval(row, row);
            panel.mainTable.scrollTo(topShow);
            panel.showEntry(ex.getEntry());
        } else {
            LOGGER.error("Problem saving file", ex);
        }

        JOptionPane.showMessageDialog(frame,
                Localization.lang("Could not save file.") + ".\n" + ex.getMessage(),
                Localization.lang("Save database"), JOptionPane.ERROR_MESSAGE);
        throw new SaveException("rt");

    } finally {
        frame.unblock();
    }

    boolean commit = true;
    if (!session.getWriter().couldEncodeAll()) {
        FormBuilder builder = FormBuilder.create()
                .layout(new FormLayout("left:pref, 4dlu, fill:pref", "pref, 4dlu, pref"));
        JTextArea ta = new JTextArea(session.getWriter().getProblemCharacters());
        ta.setEditable(false);
        builder.add(Localization.lang("The chosen encoding '%0' could not encode the following characters:",
                session.getEncoding().displayName())).xy(1, 1);
        builder.add(ta).xy(3, 1);
        builder.add(Localization.lang("What do you want to do?")).xy(1, 3);
        String tryDiff = Localization.lang("Try different encoding");
        int answer = JOptionPane.showOptionDialog(frame, builder.getPanel(), Localization.lang("Save database"),
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null,
                new String[] { Localization.lang("Save"), tryDiff, Localization.lang("Cancel") }, tryDiff);

        if (answer == JOptionPane.NO_OPTION) {
            // The user wants to use another encoding.
            Object choice = JOptionPane.showInputDialog(frame, Localization.lang("Select encoding"),
                    Localization.lang("Save database"), JOptionPane.QUESTION_MESSAGE, null,
                    Encodings.ENCODINGS_DISPLAYNAMES, encoding);
            if (choice == null) {
                commit = false;
            } else {
                Charset newEncoding = Charset.forName((String) choice);
                return saveDatabase(file, selectedOnly, newEncoding);
            }
        } else if (answer == JOptionPane.CANCEL_OPTION) {
            commit = false;
        }

    }

    try {
        if (commit) {
            session.commit(file);
            panel.setEncoding(encoding); // Make sure to remember which encoding we used.
        } else {
            session.cancel();
        }
    } catch (SaveException e) {
        int ans = JOptionPane.showConfirmDialog(null,
                Localization.lang("Save failed during backup creation") + ". "
                        + Localization.lang("Save without backup?"),
                Localization.lang("Unable to create backup"), JOptionPane.YES_NO_OPTION);
        if (ans == JOptionPane.YES_OPTION) {
            session.setUseBackup(false);
            session.commit(file);
            panel.setEncoding(encoding);
        } else {
            commit = false;
        }
    }

    return commit;
}

From source file:edu.gcsc.vrl.jfreechart.JFExport.java

/**
 * Show dialog for exporting JFreechart object.
 *///from  ww  w.  ja v  a 2  s .co  m
public void openExportDialog(JFreeChart jfreechart) {

    JFileChooser chooser = new JFileChooser();
    String path0;
    File file;

    chooser.addChoosableFileFilter(new FileNameExtensionFilter("PDF Files", "pdf"));
    chooser.addChoosableFileFilter(new FileNameExtensionFilter("JPEG Files", "jpg"));
    chooser.addChoosableFileFilter(new FileNameExtensionFilter("PNG Files", "png"));
    chooser.addChoosableFileFilter(new FileNameExtensionFilter("EPS Files", "eps"));
    chooser.addChoosableFileFilter(new FileNameExtensionFilter("SVG Files", "svg"));

    chooser.setFileFilter(new FileNameExtensionFilter("PDF Files", "pdf"));

    int returnVal = chooser.showSaveDialog(null);
    String fd = chooser.getFileFilter().getDescription();

    // Get selected FileFilter 
    String filter_extension = null;
    if (fd.equals("PNG Files")) {
        filter_extension = "png";
    }
    if (fd.equals("SVG Files")) {
        filter_extension = "svg";
    }
    if (fd.equals("JPEG Files")) {
        filter_extension = "jpg";
    }
    if (fd.equals("PDF Files")) {
        filter_extension = "pdf";
    }
    if (fd.equals("EPS Files")) {
        filter_extension = "eps";
    }

    // Cancel
    if (returnVal == JFileChooser.CANCEL_OPTION) {
        return;
    }

    // OK
    if (returnVal == JFileChooser.APPROVE_OPTION) {

        path0 = chooser.getSelectedFile().getAbsolutePath();
        //System.out.println(path0);
        try {
            file = new File(path0);
            // Get extension (if any)
            String ext = JFUtils.getExtension(file);
            // No extension -> use selected Filter
            if (ext == null) {
                file = new File(path0 + "." + filter_extension);
                ext = filter_extension;
            }

            // File exists - overwrite ?
            if (file.exists()) {
                Object[] options = { "OK", "CANCEL" };
                int answer = JOptionPane.showOptionDialog(null, "File exists - Overwrite ?", "Warning",
                        JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
                if (answer != JOptionPane.YES_OPTION) {
                    return;
                }
                //System.out.println(answer+"");
            }

            // Export file
            export(file, jfreechart);
        } catch (Exception f) {
            // I/O - Error
        }
    }
}

From source file:de.adv_online.aaa.profiltool.ProfilDialog.java

public void initialise(Converter c, Options o, ShapeChangeResult r, String xmi)
        throws ShapeChangeAbortException {

    try {//from  w  w w.j  a va2  s. c  o m
        String msg = "Akzeptieren Sie die in der mit diesem Tool ausgelieferten Datei 'Lizenzbedingungen zur Nutzung von Softwareskripten.doc' beschriebenen Lizenzbedingungen?"; // Meldung
        if (msg != null) {
            Object[] options = { "Ja", "Nein" };
            int val = JOptionPane.showOptionDialog(null, msg, "Confirmation", JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
            if (val == 1)
                System.exit(0);
        }
    } catch (Exception e) {
        System.out.println("Fehler in Dialog: " + e.toString());
    }

    options = o;

    File eapFile = new File(xmi);
    try {
        eap = eapFile.getCanonicalFile().getAbsolutePath();
    } catch (IOException e) {
        eap = "ERROR.eap";
    }

    converter = new Converter(options, r);
    result = r;
    modelTransformed = false;
    transformationRunning = false;

    StatusBoard.getStatusBoard().registerStatusReader(this);

    // frame
    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

    // panel
    newContentPane = new JPanel(new BorderLayout());
    newContentPane.setOpaque(true);
    setContentPane(newContentPane);

    newContentPane.add(createMainTab(), BorderLayout.CENTER);

    statusBar = new StatusBar();

    Box fileBox = Box.createVerticalBox();
    fileBox.add(createStartPanel());
    fileBox.add(statusBar);

    newContentPane.add(fileBox, BorderLayout.SOUTH);

    int height = 610;
    int width = 560;

    pack();

    Insets fI = getInsets();
    setSize(width + fI.right + fI.left, height + fI.top + fI.bottom);
    Dimension sD = Toolkit.getDefaultToolkit().getScreenSize();
    setLocation((sD.width - width) / 2, (sD.height - height) / 2);
    this.setMinimumSize(new Dimension(width, height));

    // frame closing
    WindowListener listener = new WindowAdapter() {
        public void windowClosing(WindowEvent w) {
            //JOptionPane.showMessageDialog(null, "Nein", "NO", JOptionPane.ERROR_MESSAGE);
            closeDialog();
        }
    };
    addWindowListener(listener);
}

From source file:com.piusvelte.taplock.server.TapLockServer.java

private static void initialize() {
    (new File(APP_PATH)).mkdir();
    if (OS == OS_WIN)
        Security.addProvider(new BouncyCastleProvider());
    System.out.println("APP_PATH: " + APP_PATH);
    try {/*  w  w w . j ava 2 s.c o  m*/
        sLogFileHandler = new FileHandler(sLog);
    } catch (SecurityException e) {
        writeLog("sLogFileHandler init: " + e.getMessage());
    } catch (IOException e) {
        writeLog("sLogFileHandler init: " + e.getMessage());
    }

    File propertiesFile = new File(sProperties);
    if (!propertiesFile.exists()) {
        try {
            propertiesFile.createNewFile();
        } catch (IOException e) {
            writeLog("propertiesFile.createNewFile: " + e.getMessage());
        }
    }

    Properties prop = new Properties();

    try {
        prop.load(new FileInputStream(sProperties));
        if (prop.isEmpty()) {
            prop.setProperty(sPassphraseKey, sPassphrase);
            prop.setProperty(sDisplaySystemTrayKey, Boolean.toString(sDisplaySystemTray));
            prop.setProperty(sDebuggingKey, Boolean.toString(sDebugging));
            prop.store(new FileOutputStream(sProperties), null);
        } else {
            if (prop.containsKey(sPassphraseKey))
                sPassphrase = prop.getProperty(sPassphraseKey);
            else
                prop.setProperty(sPassphraseKey, sPassphrase);
            if (prop.containsKey(sDisplaySystemTrayKey))
                sDisplaySystemTray = Boolean.parseBoolean(prop.getProperty(sDisplaySystemTrayKey));
            else
                prop.setProperty(sDisplaySystemTrayKey, Boolean.toString(sDisplaySystemTray));
            if (prop.containsKey(sDebuggingKey))
                sDebugging = Boolean.parseBoolean(prop.getProperty(sDebuggingKey));
            else
                prop.setProperty(sDebuggingKey, Boolean.toString(sDebugging));
        }
    } catch (FileNotFoundException e) {
        writeLog("prop load: " + e.getMessage());
    } catch (IOException e) {
        writeLog("prop load: " + e.getMessage());
    }

    if (sLogFileHandler != null) {
        sLogger = Logger.getLogger("TapLock");
        sLogger.setUseParentHandlers(false);
        sLogger.addHandler(sLogFileHandler);
        SimpleFormatter sf = new SimpleFormatter();
        sLogFileHandler.setFormatter(sf);
        writeLog("service starting");
    }

    if (sDisplaySystemTray && SystemTray.isSupported()) {
        final SystemTray systemTray = SystemTray.getSystemTray();
        Image trayIconImg = Toolkit.getDefaultToolkit()
                .getImage(TapLockServer.class.getResource("/systemtrayicon.png"));
        final TrayIcon trayIcon = new TrayIcon(trayIconImg, "Tap Lock");
        trayIcon.setImageAutoSize(true);
        PopupMenu popupMenu = new PopupMenu();
        MenuItem aboutItem = new MenuItem("About");
        CheckboxMenuItem toggleSystemTrayIcon = new CheckboxMenuItem("Display Icon in System Tray");
        toggleSystemTrayIcon.setState(sDisplaySystemTray);
        CheckboxMenuItem toggleDebugging = new CheckboxMenuItem("Debugging");
        toggleDebugging.setState(sDebugging);
        MenuItem shutdownItem = new MenuItem("Shutdown Tap Lock Server");
        popupMenu.add(aboutItem);
        popupMenu.add(toggleSystemTrayIcon);
        if (OS == OS_WIN) {
            MenuItem setPasswordItem = new MenuItem("Set password");
            popupMenu.add(setPasswordItem);
            setPasswordItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JPanel panel = new JPanel();
                    JLabel label = new JLabel("Enter your Windows account password:");
                    JPasswordField passField = new JPasswordField(32);
                    panel.add(label);
                    panel.add(passField);
                    String[] options = new String[] { "OK", "Cancel" };
                    int option = JOptionPane.showOptionDialog(null, panel, "Tap Lock", JOptionPane.NO_OPTION,
                            JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
                    if (option == 0) {
                        String password = encryptString(new String(passField.getPassword()));
                        if (password != null) {
                            Properties prop = new Properties();
                            try {
                                prop.load(new FileInputStream(sProperties));
                                prop.setProperty(sPasswordKey, password);
                                prop.store(new FileOutputStream(sProperties), null);
                            } catch (FileNotFoundException e1) {
                                writeLog("prop load: " + e1.getMessage());
                            } catch (IOException e1) {
                                writeLog("prop load: " + e1.getMessage());
                            }
                        }
                    }
                }
            });
        }
        popupMenu.add(toggleDebugging);
        popupMenu.add(shutdownItem);
        trayIcon.setPopupMenu(popupMenu);
        try {
            systemTray.add(trayIcon);
        } catch (AWTException e) {
            writeLog("systemTray.add: " + e.getMessage());
        }
        aboutItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String newline = System.getProperty("line.separator");
                newline += newline;
                JOptionPane.showMessageDialog(null, "Tap Lock" + newline + "Copyright (c) 2012 Bryan Emmanuel"
                        + newline
                        + "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version."
                        + newline
                        + "This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details."
                        + newline
                        + "You should have received a copy of the GNU General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>."
                        + newline + "Bryan Emmanuel piusvelte@gmail.com");
            }
        });
        toggleSystemTrayIcon.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                setTrayIconDisplay(e.getStateChange() == ItemEvent.SELECTED);
                if (!sDisplaySystemTray)
                    systemTray.remove(trayIcon);
            }
        });
        toggleDebugging.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                setDebugging(e.getStateChange() == ItemEvent.SELECTED);
            }
        });
        shutdownItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                shutdown();
            }
        });
    }
    synchronized (sConnectionThreadLock) {
        (sConnectionThread = new ConnectionThread()).start();
    }
}