Example usage for javax.swing JOptionPane DEFAULT_OPTION

List of usage examples for javax.swing JOptionPane DEFAULT_OPTION

Introduction

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

Prototype

int DEFAULT_OPTION

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

Click Source Link

Document

Type meaning Look and Feel should not supply any options -- only use the options from the JOptionPane.

Usage

From source file:com.pingtel.sipviewer.SIPViewerFrame.java

public void applyAliasesFile(String strAliasesFile) {
    try {/*from w  w  w . j  av  a 2s. c o  m*/
        FileReader fr = new FileReader(strAliasesFile);

        BufferedReader reader = new BufferedReader(fr);
        String strLine = reader.readLine();
        while (strLine != null) {
            int pos = strLine.indexOf("=");
            if (pos > 0) {
                String strValue = strLine.substring(0, pos);
                String strKey = strLine.substring(pos + 1);

                strKey = strKey.trim();
                strValue = strValue.trim();

                // System.out.println("AddAlias: " + strValue + " -> " +
                // strKey) ;

                m_model.removeKey(strValue);
                m_model.addKeyAlias(strKey, strValue);
                m_model.reindexData();
            }

            strLine = reader.readLine();
        }

        reader.close();
        fr.close();
    } catch (Exception e) {
        System.out.println("Unable to apply aliases file: " + strAliasesFile);

        JOptionPane.showConfirmDialog(null, "Unable to apply aliases file: " + strAliasesFile, "Error",
                JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null);
        e.printStackTrace();
        this.dispose();
    }
}

From source file:net.menthor.editor.v2.util.Util.java

/** Helper method for constructing an always-on-top modal dialog. */
public static Object show(String title, int type, Object message, Object[] options, Object initialOption) {
    if (options == null) {
        options = new Object[] { "Ok" };
        initialOption = "Ok";
    }// w ww  . j ava  2 s  .com
    JOptionPane p = new JOptionPane(message, type, JOptionPane.DEFAULT_OPTION, null, options, initialOption);
    p.setInitialValue(initialOption);
    JDialog d = p.createDialog(null, title);
    p.selectInitialValue();
    d.setAlwaysOnTop(true);
    d.setVisible(true);
    d.dispose();
    return p.getValue();
}

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;//www. j a  v a2 s. 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:edu.gcsc.vrl.jfreechart.JFExport.java

/**
 * Show dialog for exporting JFreechart object.
 */// www .  j a v  a2  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:me.childintime.childintime.InitialSetup.java

/**
 * Show the confirmation dialog.//  w w  w . j  a  v  a2 s. c o m
 *
 * @return True if the user agree'd, false if not.
 */
private boolean showConfirmationDialog() {
    // Create a list with the buttons to show in the option dialog
    List<String> buttons = new ArrayList<>();
    buttons.add("Continue");
    buttons.add("Quit");

    // Reverse the button list if we're on a Mac OS X system
    if (Platform.isMacOsX())
        Collections.reverse(buttons);

    // Show the option dialog
    final int option = JOptionPane.showOptionDialog(this.progressDialog,
            "This is the first time you're using " + App.APP_NAME + " on this system.\n"
                    + "Some application files are required to be installed.\n"
                    + "Please Continue and allow us to set things up for you.",
            App.APP_NAME + " - Initial setup", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null,
            buttons.toArray(), buttons.get(!Platform.isMacOsX() ? 0 : 1));

    // Determine, set and return the result
    this.confirmDialogAgree = (option == (!Platform.isMacOsX() ? 0 : 1));
    return this.confirmDialogAgree;
}

From source file:com.ln.gui.Main.java

@SuppressWarnings("unchecked")
public Main() {/*  w  ww.ja  va  2  s . co m*/
    System.gc();
    setIconImage(Toolkit.getDefaultToolkit().getImage(Configuration.mydir + "\\resources\\icons\\ln6464.png"));
    DateFormat dd = new SimpleDateFormat("dd");
    DateFormat dh = new SimpleDateFormat("HH");
    DateFormat dm = new SimpleDateFormat("mm");
    Date day = new Date();
    Date hour = new Date();
    Date minute = new Date();
    dayd = Integer.parseInt(dd.format(day));
    hourh = Integer.parseInt(dh.format(hour));
    minutem = Integer.parseInt(dm.format(minute));
    setTitle("Liquid Notify Revision 2");
    Description.setBackground(Color.WHITE);
    Description.setContentType("text/html");
    Description.setEditable(false);
    Getcalendar.Main();
    HyperlinkListener hyperlinkListener = new ActivatedHyperlinkListener(f, Description);
    Description.addHyperlinkListener(hyperlinkListener);
    //Add components
    setContentPane(contentPane);
    setJMenuBar(menuBar);
    contentPane.setLayout(
            new MigLayout("", "[220px:230.00:220,grow][209.00px:n:5000,grow]", "[22px][][199.00,grow][grow]"));
    eventsbtn.setToolTipText("Displays events currently set to notify");
    eventsbtn.setMinimumSize(new Dimension(220, 23));
    eventsbtn.setMaximumSize(new Dimension(220, 23));
    contentPane.add(eventsbtn, "cell 0 0");
    NewsArea.setBackground(Color.WHITE);
    NewsArea.setBorder(new BevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, Color.LIGHT_GRAY, Color.DARK_GRAY,
            Color.DARK_GRAY));
    NewsArea.setMinimumSize(new Dimension(20, 22));
    NewsArea.setMaximumSize(new Dimension(10000, 22));
    contentPane.add(NewsArea, "cell 1 0,growx,aligny top");
    menuBar.add(File);
    JMenuItem Settings = new JMenuItem("Settings");
    Settings.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\settings.png"));
    Settings.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Settings setup = new Settings();
            setup.setVisible(true);
            setup.setLocationRelativeTo(rootPane);
        }
    });
    File.add(Settings);
    File.add(mntmNewMenuItem);
    Tray.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\ln1616.png"));
    File.add(Tray);
    Exit.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\exit.png"));
    File.add(Exit);

    menuBar.add(mnNewMenu);

    Update.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\update.png"));
    Update.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                URL localURL = new URL("http://jiiks.net23.net/tlnotify/online.html");
                URLConnection localURLConnection = localURL.openConnection();
                BufferedReader localBufferedReader = new BufferedReader(
                        new InputStreamReader(localURLConnection.getInputStream()));
                String str = localBufferedReader.readLine();
                if (!str.contains("YES")) {
                    String st2221 = "Updates server appears to be offline";
                    JOptionPane pane1 = new JOptionPane(st2221, JOptionPane.WARNING_MESSAGE,
                            JOptionPane.DEFAULT_OPTION);
                    JDialog dialog1 = pane1.createDialog("Update");
                    dialog1.setLocationRelativeTo(null);
                    dialog1.setVisible(true);
                    dialog1.setAlwaysOnTop(true);
                } else if (str.contains("YES")) {
                    URL localURL2 = new URL("http://jiiks.net23.net/tlnotify/latestversion.html");
                    URLConnection localURLConnection1 = localURL2.openConnection();
                    BufferedReader localBufferedReader2 = new BufferedReader(
                            new InputStreamReader(localURLConnection1.getInputStream()));
                    String str2 = localBufferedReader2.readLine();
                    Updatechecker.latestver = str2;
                    if (Integer.parseInt(str2) <= Configuration.version) {
                        String st2221 = "No updates available =(";
                        JOptionPane pane1 = new JOptionPane(st2221, JOptionPane.WARNING_MESSAGE,
                                JOptionPane.DEFAULT_OPTION);
                        JDialog dialog1 = pane1.createDialog("Update");
                        dialog1.setLocationRelativeTo(null);
                        dialog1.setVisible(true);
                        dialog1.setAlwaysOnTop(true);
                    } else if (Integer.parseInt(str2) > Configuration.version) {
                        String st2221 = "Updates available!";
                        JOptionPane pane1 = new JOptionPane(st2221, JOptionPane.WARNING_MESSAGE,
                                JOptionPane.DEFAULT_OPTION);
                        JDialog dialog1 = pane1.createDialog("Update");
                        dialog1.setLocationRelativeTo(null);
                        dialog1.setVisible(true);
                        dialog1.setAlwaysOnTop(true);

                        Updatechecker upd = new Updatechecker();
                        upd.setVisible(true);
                        upd.setLocationRelativeTo(rootPane);
                        upd.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
                    }
                }
            } catch (MalformedURLException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }

    });
    mnNewMenu.add(Update);
    JMenuItem About = new JMenuItem("About");
    About.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\about.png"));
    About.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            About a = new About();
            a.setVisible(true);
            a.setLocationRelativeTo(rootPane);
            a.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        }
    });
    mnNewMenu.add(About);
    JMenuItem Github = new JMenuItem("Github");
    Github.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\github.png"));
    Github.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String url = "https://github.com/Jiiks/Liquid-Notify-Rev2";
            try {
                java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    });
    mnNewMenu.add(Github);
    JMenuItem Thread = new JMenuItem("Thread");
    Thread.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\liquid.png"));
    Thread.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String url = "http://www.teamliquid.net/forum/viewmessage.php?topic_id=318184";
            try {
                java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    });
    mnNewMenu.add(Thread);
    Refreshbtn.setToolTipText("Refreshes calendar, please don't spam ^_^");
    Refreshbtn.setPreferredSize(new Dimension(90, 20));
    Refreshbtn.setMinimumSize(new Dimension(100, 20));
    Refreshbtn.setMaximumSize(new Dimension(100, 20));
    contentPane.add(Refreshbtn, "flowx,cell 0 1,alignx left");
    //Components to secondary panel   
    Titlebox = new JComboBox();
    contentPane.add(Titlebox, "cell 1 1,growx,aligny top");
    Titlebox.setMinimumSize(new Dimension(20, 20));
    Titlebox.setMaximumSize(new Dimension(10000, 20));
    //Set other
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 686, 342);
    contentPane.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
    NewsArea.setEnabled(false);
    NewsArea.setEditable(false);
    NewsArea.setText("News: " + News);
    contentPane.add(panel, "cell 0 2,grow");
    panel.setLayout(null);
    final JCalendar calendar = new JCalendar();
    calendar.getMonthChooser().setPreferredSize(new Dimension(120, 20));
    calendar.getMonthChooser().setMinimumSize(new Dimension(120, 24));
    calendar.getYearChooser().setLocation(new Point(20, 0));
    calendar.getYearChooser().setMaximum(100);
    calendar.getYearChooser().setMaximumSize(new Dimension(100, 2147483647));
    calendar.getYearChooser().setMinimumSize(new Dimension(50, 20));
    calendar.getYearChooser().setPreferredSize(new Dimension(50, 20));
    calendar.getYearChooser().getSpinner().setPreferredSize(new Dimension(100, 20));
    calendar.getYearChooser().getSpinner().setMinimumSize(new Dimension(100, 20));
    calendar.getMonthChooser().getSpinner().setPreferredSize(new Dimension(119, 20));
    calendar.getMonthChooser().getSpinner().setMinimumSize(new Dimension(120, 24));
    calendar.getDayChooser().getDayPanel().setFont(new Font("Tahoma", Font.PLAIN, 11));
    calendar.setDecorationBordersVisible(true);
    calendar.setTodayButtonVisible(true);
    calendar.setBackground(Color.LIGHT_GRAY);
    calendar.setBounds(0, 0, 220, 199);
    calendar.getDate();
    calendar.setWeekOfYearVisible(false);
    calendar.setDecorationBackgroundVisible(false);
    calendar.setMaxDayCharacters(2);
    calendar.getDayChooser().setFont(new Font("Tahoma", Font.PLAIN, 10));
    panel.add(calendar);
    Descriptionscrollpane.setLocation(new Point(100, 100));
    Descriptionscrollpane.setMaximumSize(new Dimension(10000, 10000));
    Descriptionscrollpane.setMinimumSize(new Dimension(20, 200));
    Description.setLocation(new Point(100, 100));
    Description.setBorder(new BevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, Color.LIGHT_GRAY,
            Color.DARK_GRAY, Color.DARK_GRAY));
    Description.setMaximumSize(new Dimension(1000, 400));
    Description.setMinimumSize(new Dimension(400, 200));
    contentPane.add(Descriptionscrollpane, "cell 1 2 1 2,growx,aligny top");
    Descriptionscrollpane.setViewportView(Description);
    verticalStrut.setMinimumSize(new Dimension(12, 20));
    contentPane.add(verticalStrut, "cell 0 1");
    Notify.setToolTipText("Adds selected event to notify event list.");
    Notify.setHorizontalTextPosition(SwingConstants.CENTER);
    Notify.setPreferredSize(new Dimension(100, 20));
    Notify.setMinimumSize(new Dimension(100, 20));
    Notify.setMaximumSize(new Dimension(100, 20));
    contentPane.add(Notify, "cell 0 1,alignx right");
    calendar.getMonthChooser().addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            month = calendar.getMonthChooser().getMonth();
            Parser.parse();
        }
    });

    calendar.getDayChooser().addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            try {
                int h = calendar.getMonthChooser().getMonth();
                @SuppressWarnings("deprecation")
                int date = calendar.getDate().getDate();
                int month = calendar.getMonthChooser().getMonth() + 1;
                globmonth = calendar.getMonthChooser().getMonth();
                sdate = date;
                datestring = Integer.toString(sdate);
                monthstring = Integer.toString(month);
                String[] Hours = Betaparser.Hours;
                String[] Titles = Betaparser.STitle;
                String[] Full = new String[Hours.length];
                String[] Minutes = Betaparser.Minutes;
                String[] Des = Betaparser.Description;
                String[] Des2 = new String[Betaparser.Description.length];
                String Seconds = "00";
                String gg;
                int[] IntHours = new int[Hours.length];
                int[] IntMins = new int[Hours.length];
                int Events = 0;
                monthday = monthstring + "|" + datestring + "|";
                Titlebox.removeAllItems();
                for (int a = 0; a != Hours.length; a++) {
                    IntHours[a] = Integer.parseInt(Hours[a]);
                    IntMins[a] = Integer.parseInt(Minutes[a]);
                }
                for (int i1 = 0; i1 != Hours.length; i1++) {
                    if (Betaparser.Events[i1].startsWith(monthday)) {
                        Full[i1] = String.format("%02d:%02d", IntHours[i1], IntMins[i1]) + " | " + Titles[i1];
                        Titlebox.addItem(Full[i1]);
                    }
                }
            } catch (Exception e1) {
                //Catching mainly due to boot property change            
            }
        }
    });
    Image image = Toolkit.getDefaultToolkit().getImage(Configuration.mydir + "\\resources\\icons\\ln1616.png");
    final SystemTray tray = SystemTray.getSystemTray();
    ActionListener listener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            setVisible(true);
        }
    };
    PopupMenu popup = new PopupMenu();
    MenuItem defaultItem = new MenuItem();
    defaultItem.addActionListener(listener);
    TrayIcon trayIcon = null;
    trayIcon = new TrayIcon(image, "LiquidNotify Revision 2", popup);

    trayIcon.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent arg0) {
            setVisible(true);
        }
    });//
    try {
        tray.add(trayIcon);
    } catch (AWTException e) {
        System.err.println(e);
    }
    if (trayIcon != null) {
        trayIcon.setImage(image);
    }

    Tray.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            setVisible(false);
        }
    });

    Titlebox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Descparser.parsedesc();
        }
    });

    Refreshbtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Getcalendar.Main();
            Descparser.parsedesc();
        }
    });

    Notify.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            NOTIFY = Descparser.TTT;
            NOTIFYD = Descparser.DDD;
            NOTIFYH = Descparser.HHH;
            NOTIFYM = Descparser.MMM;
            int i = events;
            NOA[i] = NOTIFY;
            NOD[i] = NOTIFYD;
            NOH[i] = NOTIFYH;
            NOM[i] = NOTIFYM;
            Eventlist[i] = "Starts in: " + Integer.toString(NOD[i]) + " Days " + Integer.toString(NOH[i])
                    + " Hours " + Integer.toString(NOM[i]) + " Minutes " + " | " + NOA[i];
            events = events + 1;
            Notifylist si = new Notifylist();
            si.setVisible(false);
            si.setBounds(1, 1, 1, 1);
            si.dispose();
            if (thread.getState().name().equals("PENDING")) {
                thread.execute();
            }
        }
    });
    eventsbtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Notifylist list = new Notifylist();
            if (played == 1) {
                asd.close();
                played = 0;
            }
            list.setVisible(true);
            list.setLocationRelativeTo(rootPane);
            list.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        }
    });

    mntmNewMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (thread.getState().name().equals("PENDING")) {
                thread.execute();
            }
            Userstreams us = new Userstreams();
            us.setVisible(true);
            us.setLocationRelativeTo(rootPane);
        }
    });

    Exit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            //Absolute exit
            JOptionPane.showMessageDialog(rootPane, "Bye bye :(", "Exit", JOptionPane.INFORMATION_MESSAGE);
            Runtime ln = Runtime.getRuntime();
            ln.gc();
            final Frame[] allf = Frame.getFrames();
            final Window[] allw = Window.getWindows();
            for (final Window allwindows : allw) {
                allwindows.dispose();
            }
            for (final Frame allframes : allf) {
                allframes.dispose();
                System.exit(0);
            }
        }
    });
}

From source file:com.paniclauncher.data.Instance.java

public void launch() {
    final Account account = App.settings.getAccount();
    if (account == null) {
        String[] options = { App.settings.getLocalizedString("common.ok") };
        JOptionPane.showOptionDialog(App.settings.getParent(),
                App.settings.getLocalizedString("instance.noaccount"),
                App.settings.getLocalizedString("instance.noaccountselected"), JOptionPane.DEFAULT_OPTION,
                JOptionPane.ERROR_MESSAGE, null, options, options[0]);
        App.settings.setMinecraftLaunched(false);
    } else {/* www .jav a  2 s  . c om*/
        String username = account.getUsername();
        String password = account.getPassword();
        if (!account.isRemembered()) {
            JPanel panel = new JPanel();
            panel.setLayout(new BorderLayout());
            JLabel passwordLabel = new JLabel(
                    App.settings.getLocalizedString("instance.enterpassword", account.getMinecraftUsername()));
            JPasswordField passwordField = new JPasswordField();
            panel.add(passwordLabel, BorderLayout.NORTH);
            panel.add(passwordField, BorderLayout.CENTER);
            int ret = JOptionPane.showConfirmDialog(App.settings.getParent(), panel,
                    App.settings.getLocalizedString("instance.enterpasswordtitle"),
                    JOptionPane.OK_CANCEL_OPTION);
            if (ret == JOptionPane.OK_OPTION) {
                password = new String(passwordField.getPassword());
            } else {
                App.settings.setMinecraftLaunched(false);
                return;
            }
        }
        boolean loggedIn = false;
        String url = null;
        String sess = null;
        String auth = null;
        if (!App.settings.isInOfflineMode()) {
            if (isNewLaunchMethod()) {
                String result = Utils.newLogin(username, password);
                if (result == null) {
                    loggedIn = true;
                    sess = "token:0:0";
                } else {
                    JSONParser parser = new JSONParser();
                    try {
                        Object obj = parser.parse(result);
                        JSONObject jsonObject = (JSONObject) obj;
                        if (jsonObject.containsKey("accessToken")) {
                            String accessToken = (String) jsonObject.get("accessToken");
                            JSONObject profile = (JSONObject) jsonObject.get("selectedProfile");
                            String profileID = (String) profile.get("id");
                            sess = "token:" + accessToken + ":" + profileID;
                            loggedIn = true;
                        } else {
                            auth = (String) jsonObject.get("errorMessage");
                        }
                    } catch (ParseException e1) {
                        App.settings.getConsole().logStackTrace(e1);
                    }
                }
            } else {
                try {
                    url = "https://login.minecraft.net/?user=" + URLEncoder.encode(username, "UTF-8")
                            + "&password=" + URLEncoder.encode(password, "UTF-8") + "&version=999";
                } catch (UnsupportedEncodingException e1) {
                    App.settings.getConsole().logStackTrace(e1);
                }
                auth = Utils.urlToString(url);
                if (auth == null) {
                    loggedIn = true;
                    sess = "0";
                } else {
                    if (auth.contains(":")) {
                        String[] parts = auth.split(":");
                        if (parts.length == 5) {
                            loggedIn = true;
                            sess = parts[3];
                        }
                    }
                }
            }
        } else {
            loggedIn = true;
            sess = "token:0:0";
        }
        if (!loggedIn) {
            String[] options = { App.settings.getLocalizedString("common.ok") };
            JOptionPane
                    .showOptionDialog(App.settings.getParent(),
                            "<html><center>" + App.settings.getLocalizedString("instance.errorloggingin",
                                    "<br/><br/>" + auth) + "</center></html>",
                            App.settings.getLocalizedString("instance.errorloggingintitle"),
                            JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]);
            App.settings.setMinecraftLaunched(false);
        } else {
            final String session = sess;
            Thread launcher = new Thread() {
                public void run() {
                    try {
                        long start = System.currentTimeMillis();
                        if (App.settings.getParent() != null) {
                            App.settings.getParent().setVisible(false);
                        }
                        Process process = null;
                        if (isNewLaunchMethod()) {
                            process = NewMCLauncher.launch(account, Instance.this, session);
                        } else {
                            process = MCLauncher.launch(account, Instance.this, session);
                        }
                        App.settings.showKillMinecraft(process);
                        InputStream is = process.getInputStream();
                        InputStreamReader isr = new InputStreamReader(is);
                        BufferedReader br = new BufferedReader(isr);
                        String line;
                        while ((line = br.readLine()) != null) {
                            App.settings.getConsole().logMinecraft(line);
                        }
                        App.settings.hideKillMinecraft();
                        if (App.settings.getParent() != null) {
                            App.settings.getParent().setVisible(true);
                        }
                        long end = System.currentTimeMillis();
                        if (App.settings.isInOfflineMode()) {
                            App.settings.checkOnlineStatus();
                        }
                        App.settings.setMinecraftLaunched(false);
                        if (!App.settings.isInOfflineMode()) {
                            if (App.settings.isUpdatedFiles()) {
                                App.settings.reloadLauncherData();
                            }
                        }
                    } catch (IOException e1) {
                        App.settings.getConsole().logStackTrace(e1);
                    }
                }
            };
            launcher.start();
        }
    }
}

From source file:model.settings.ReadSettings.java

/**
 * checks whether program information on current workspace exist.
 * @return if workspace is now set./*  w  w w .  ja v  a 2 s .c o m*/
 */
public static String install() {
    boolean installed = false;
    String wsLocation = "";
    /*
     * does program root directory exist?
     */
    if (new File(PROGRAM_LOCATION).exists()) {

        //try to read 
        try {
            wsLocation = readFromFile(PROGRAM_SETTINGS_LOCATION);

            installed = new File(wsLocation).exists();
            if (!installed) {
                wsLocation = "";
            }

        } catch (FileNotFoundException e) {
            System.out.println("file not found " + e);
            showErrorMessage();
        } catch (IOException e) {
            System.out.println("io" + e);
            showErrorMessage();
        }
    }

    //if settings not found.
    if (!installed) {

        new File(PROGRAM_LOCATION).mkdir();
        try {

            //create new file chooser
            JFileChooser jc = new JFileChooser();

            //sets the text and language of all the components in JFileChooser
            UIManager.put("FileChooser.openDialogTitleText", "Open");
            UIManager.put("FileChooser.lookInLabelText", "LookIn");
            UIManager.put("FileChooser.openButtonText", "Open");
            UIManager.put("FileChooser.cancelButtonText", "Cancel");
            UIManager.put("FileChooser.fileNameLabelText", "FileName");
            UIManager.put("FileChooser.filesOfTypeLabelText", "TypeFiles");
            UIManager.put("FileChooser.openButtonToolTipText", "OpenSelectedFile");
            UIManager.put("FileChooser.cancelButtonToolTipText", "Cancel");
            UIManager.put("FileChooser.fileNameHeaderText", "FileName");
            UIManager.put("FileChooser.upFolderToolTipText", "UpOneLevel");
            UIManager.put("FileChooser.homeFolderToolTipText", "Desktop");
            UIManager.put("FileChooser.newFolderToolTipText", "CreateNewFolder");
            UIManager.put("FileChooser.listViewButtonToolTipText", "List");
            UIManager.put("FileChooser.newFolderButtonText", "CreateNewFolder");
            UIManager.put("FileChooser.renameFileButtonText", "RenameFile");
            UIManager.put("FileChooser.deleteFileButtonText", "DeleteFile");
            UIManager.put("FileChooser.filterLabelText", "TypeFiles");
            UIManager.put("FileChooser.detailsViewButtonToolTipText", "Details");
            UIManager.put("FileChooser.fileSizeHeaderText", "Size");
            UIManager.put("FileChooser.fileDateHeaderText", "DateModified");
            SwingUtilities.updateComponentTreeUI(jc);

            jc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            jc.setMultiSelectionEnabled(false);

            final String informationMsg = "Please select the workspace folder. \n"
                    + "By default, the new files are saved in there. \n\n"
                    + "Is changed simply by using the Save-As option.\n"
                    + "If no folder is specified, the default worspace folder \n"
                    + "is the home directory of the current user.";
            final int response = JOptionPane.showConfirmDialog(jc, informationMsg, "Select workspace folder",
                    JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE);

            final String defaultSaveLocation = System.getProperty("user.home")
                    + System.getProperty("file.separator");
            File f;
            if (response != JOptionPane.NO_OPTION) {

                //fetch selected file
                f = jc.getSelectedFile();
                jc.showDialog(null, "select");
            } else {
                f = new File(defaultSaveLocation);
            }

            printInformation();

            if (f == null) {
                f = new File(defaultSaveLocation);
            }
            //if file selected
            if (f != null) {

                //if the file exists
                if (f.exists()) {
                    writeToFile(PROGRAM_SETTINGS_LOCATION, ID_PROGRAM_LOCATION + "\n" + f.getAbsolutePath());
                } else {

                    //open message dialog
                    JOptionPane.showConfirmDialog(null, "Folder does " + "not exist",
                            "Error creating workspace", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE,
                            null);
                }

                //recall install
                return install();
            }

        } catch (IOException e) {
            System.out.println(e);
            JOptionPane.showConfirmDialog(null, "An exception occured." + " Try again later.",
                    "Error creating workspace", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null);
        }
    }

    if (System.getProperty("os.name").equals("Mac OS X")) {

        installOSX();
    } else if (System.getProperty("os.name").equals("Linux")) {
        installLinux();
    } else if (System.getProperty("os.name").equals("Windows")) {
        installWindows();
    }

    return wsLocation;

}

From source file:net.chaosserver.timelord.swingui.Timelord.java

/**
 * Returns if the system is already running based on the creation of a lock
 * file that is deleted when the JVM exits and creates a new instance of the
 * lockfile for this JVM. If the lockfile is detected it presents a dialog
 * giving an option for the end user to overwrite the lock file.
 *
 * @return indicates another instance of timelord is already running
 *//* www . jav  a2  s  .c  o  m*/
public boolean isAlreadyRunning() {
    boolean alreadyRunning = false;
    File homeDirectory = new File(System.getProperty("user.home"));
    File lockFile = new File(homeDirectory, "Timelord.lockfile");

    if (lockFile.exists()) {
        String startAnyway = "Start Anyway";
        String dontStart = "Cancel Start";
        Object[] options = { dontStart, startAnyway };
        int result = JOptionPane.showOptionDialog(null,
                "A lockfile for an instance of timelord " + "has been found.  If you are already "
                        + "running timelord, click \"" + dontStart + "\" and use the running program.",
                "Timelord Already Running", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
                options, dontStart);

        if (result == 0) {
            alreadyRunning = true;
        }
    }

    if (!alreadyRunning) {
        try {
            lockFile.createNewFile();
            lockFile.deleteOnExit();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    return alreadyRunning;
}

From source file:esmska.gui.AboutFrame.java

private void licenseButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_licenseButtonActionPerformed
    //show licence
    try {//from  ww w  . j  a  v  a 2s  . c  o m
        logger.fine("Showing license...");
        String license = IOUtils.toString(getClass().getResourceAsStream(RES + "license.txt"), "UTF-8");
        final String agpl = IOUtils.toString(getClass().getResourceAsStream(RES + "gnu-agpl.txt"), "UTF-8");
        license = MiscUtils.escapeHtml(license);
        license = license.replaceAll("GNU Affero General Public License",
                "<a href=\"agpl\">GNU Affero General Public License</a>");

        final JTextPane tp = new JTextPane();
        tp.setContentType("text/html; charset=UTF-8");
        tp.setText("<html><pre>" + license + "</pre></html>");
        tp.setEditable(false);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        tp.setPreferredSize(new Dimension((int) d.getWidth() / 2, (int) d.getHeight() / 2)); //reasonable size
        tp.setCaretPosition(0);
        //make links clickable
        tp.addHyperlinkListener(new HyperlinkListener() {
            @Override
            public void hyperlinkUpdate(final HyperlinkEvent e) {
                if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                    logger.fine("Showing GNU AGPL...");
                    tp.setText(null);
                    tp.setContentType("text/plain");
                    tp.setText(agpl);
                    tp.setCaretPosition(0);
                }
            }
        });

        String option = l10n.getString("AboutFrame.Acknowledge");
        JOptionPane op = new JOptionPane(new JScrollPane(tp), JOptionPane.INFORMATION_MESSAGE,
                JOptionPane.DEFAULT_OPTION, null, new Object[] { option }, option);
        JDialog dialog = op.createDialog(this, l10n.getString("AboutFrame.License"));
        dialog.setResizable(true);
        dialog.pack();
        dialog.setVisible(true);
    } catch (IOException ex) {
        logger.log(Level.WARNING, "Could not show license", ex);
    }
}