Example usage for javax.swing JOptionPane WARNING_MESSAGE

List of usage examples for javax.swing JOptionPane WARNING_MESSAGE

Introduction

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

Prototype

int WARNING_MESSAGE

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

Click Source Link

Document

Used for warning messages.

Usage

From source file:jamel.gui.JamelWindow.java

/**
 * Shows a dialog that indicates the bank failure.
 *//*w ww.  j  a v a 2  s. c o  m*/
public void failure() {
    println("<font color=red>" + JamelObject.getCurrentPeriod().toString() + " Bank Failure</font>");
    buttonBar.pause(true);
    JOptionPane.showMessageDialog(this, "Bank Failure", "Failure", JOptionPane.WARNING_MESSAGE);
}

From source file:components.DialogDemo.java

private JPanel createIconDialogBox() {
    JButton showItButton = null;//from   w ww . j  av a 2  s .  com

    final int numButtons = 6;
    JRadioButton[] radioButtons = new JRadioButton[numButtons];
    final ButtonGroup group = new ButtonGroup();

    final String plainCommand = "plain";
    final String infoCommand = "info";
    final String questionCommand = "question";
    final String errorCommand = "error";
    final String warningCommand = "warning";
    final String customCommand = "custom";

    radioButtons[0] = new JRadioButton("Plain (no icon)");
    radioButtons[0].setActionCommand(plainCommand);

    radioButtons[1] = new JRadioButton("Information icon");
    radioButtons[1].setActionCommand(infoCommand);

    radioButtons[2] = new JRadioButton("Question icon");
    radioButtons[2].setActionCommand(questionCommand);

    radioButtons[3] = new JRadioButton("Error icon");
    radioButtons[3].setActionCommand(errorCommand);

    radioButtons[4] = new JRadioButton("Warning icon");
    radioButtons[4].setActionCommand(warningCommand);

    radioButtons[5] = new JRadioButton("Custom icon");
    radioButtons[5].setActionCommand(customCommand);

    for (int i = 0; i < numButtons; i++) {
        group.add(radioButtons[i]);
    }
    radioButtons[0].setSelected(true);

    showItButton = new JButton("Show it!");
    showItButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String command = group.getSelection().getActionCommand();

            //no icon
            if (command == plainCommand) {
                JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green.", "A plain message",
                        JOptionPane.PLAIN_MESSAGE);
                //information icon
            } else if (command == infoCommand) {
                JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green.",
                        "Inane informational dialog", JOptionPane.INFORMATION_MESSAGE);

                //XXX: It doesn't make sense to make a question with
                //XXX: only one button.
                //XXX: See "Yes/No (but not in those words)" for a better solution.
                //question icon
            } else if (command == questionCommand) {
                JOptionPane.showMessageDialog(frame,
                        "You shouldn't use a message dialog " + "(like this)\n" + "for a question, OK?",
                        "Inane question", JOptionPane.QUESTION_MESSAGE);
                //error icon
            } else if (command == errorCommand) {
                JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green.", "Inane error",
                        JOptionPane.ERROR_MESSAGE);
                //warning icon
            } else if (command == warningCommand) {
                JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green.", "Inane warning",
                        JOptionPane.WARNING_MESSAGE);
                //custom icon
            } else if (command == customCommand) {
                JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green.", "Inane custom dialog",
                        JOptionPane.INFORMATION_MESSAGE, icon);
            }
        }
    });

    return create2ColPane(iconDesc + ":", radioButtons, showItButton);
}

From source file:net.sf.jabref.util.Util.java

/**
 * Warns the user of undesired side effects of an explicit assignment/removal of entries to/from this group.
 * Currently there are four types of groups: AllEntriesGroup, SearchGroup - do not support explicit assignment.
 * ExplicitGroup - never modifies entries. KeywordGroup - only this modifies entries upon assignment/removal.
 * Modifications are acceptable unless they affect a standard field (such as "author") besides the "keywords" field.
 *
 * @param parent The Component used as a parent when displaying a confirmation dialog.
 * @return true if the assignment has no undesired side effects, or the user chose to perform it anyway. false
 * otherwise (this indicates that the user has aborted the assignment).
 *///ww  w.  j  ava2s  .c  o m
public static boolean warnAssignmentSideEffects(List<AbstractGroup> groups, Component parent) {
    List<String> affectedFields = new ArrayList<>();
    for (AbstractGroup group : groups) {
        if (group instanceof KeywordGroup) {
            KeywordGroup kg = (KeywordGroup) group;
            String field = kg.getSearchField().toLowerCase();
            if ("keywords".equals(field)) {
                continue; // this is not undesired
            }
            int len = InternalBibtexFields.numberOfPublicFields();
            for (int i = 0; i < len; ++i) {
                if (field.equals(InternalBibtexFields.getFieldName(i))) {
                    affectedFields.add(field);
                    break;
                }
            }
        }
    }
    if (affectedFields.isEmpty()) {
        return true; // no side effects
    }

    // show a warning, then return
    StringBuilder message = new StringBuilder(
            Localization.lang("This action will modify the following field(s) in at least one entry each:"))
                    .append('\n');
    for (String affectedField : affectedFields) {
        message.append(affectedField).append('\n');
    }
    message.append(Localization.lang("This could cause undesired changes to your entries.")).append('\n')
            .append("It is recommended that you change the grouping field in your group definition to \"keywords\" or a non-standard name.")
            .append("\n\n").append(Localization.lang("Do you still want to continue?"));
    int choice = JOptionPane.showConfirmDialog(parent, message, Localization.lang("Warning"),
            JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
    return choice != JOptionPane.NO_OPTION;

    // if (groups instanceof KeywordGroup) {
    // KeywordGroup kg = (KeywordGroup) groups;
    // String field = kg.getSearchField().toLowerCase();
    // if (field.equals("keywords"))
    // return true; // this is not undesired
    // for (int i = 0; i < GUIGlobals.ALL_FIELDS.length; ++i) {
    // if (field.equals(GUIGlobals.ALL_FIELDS[i])) {
    // // show a warning, then return
    // String message = Globals ...
    // .lang(
    // "This action will modify the \"%0\" field "
    // + "of your entries.\nThis could cause undesired changes to "
    // + "your entries, so it is\nrecommended that you change the grouping
    // field "
    // + "in your group\ndefinition to \"keywords\" or a non-standard name."
    // + "\n\nDo you still want to continue?",
    // field);
    // int choice = JOptionPane.showConfirmDialog(parent, message,
    // Globals.lang("Warning"), JOptionPane.YES_NO_OPTION,
    // JOptionPane.WARNING_MESSAGE);
    // return choice != JOptionPane.NO_OPTION;
    // }
    // }
    // }
    // return true; // found no side effects
}

From source file:edu.ku.brc.specify.tasks.InfoRequestTask.java

/**
 * Creates an Excel SpreadSheet or CVS file and attaches it to an email and send it to an agent.
 *//* w w w  .j av a 2s  . c o m*/
public void createAndSendEMail() {
    FormViewObj formViewObj = getCurrentFormViewObj();
    if (formViewObj != null) // Should never happen
    {
        InfoRequest infoRequest = (InfoRequest) formViewObj.getDataObj();
        Agent toAgent = infoRequest.getAgent();

        boolean sendEMailTmp = true; // default to true
        Component comp = formViewObj.getControlByName("sendEMail");
        if (comp instanceof JCheckBox) {
            sendEMailTmp = ((JCheckBox) comp).isSelected();
        }
        final boolean sendEMail = sendEMailTmp;

        MultiView mv = formViewObj.getSubView("InfoRequestColObj");
        if (mv != null && sendEMail) {
            final Viewable viewable = mv.getCurrentView();
            if (viewable instanceof TableViewObj) {
                final Hashtable<String, String> emailPrefs = new Hashtable<String, String>();
                if (!isEMailPrefsOK(emailPrefs)) {
                    JOptionPane.showMessageDialog(UIRegistry.getTopWindow(),
                            getResourceString("NO_EMAIL_PREF_INFO"),
                            getResourceString("NO_EMAIL_PREF_INFO_TITLE"), JOptionPane.WARNING_MESSAGE);
                    return;
                }

                final File tempExcelFileName = TableModel2Excel.getTempExcelName();

                AppPreferences appPrefs = AppPreferences.getLocalPrefs();
                final Hashtable<String, String> values = new Hashtable<String, String>();
                values.put("to", toAgent.getEmail() != null ? toAgent.getEmail() : "");
                values.put("from", appPrefs.get("settings.email.email", ""));
                values.put("subject", String.format(getResourceString("INFO_REQUEST_SUBJECT"),
                        new Object[] { infoRequest.getIdentityTitle() }));
                values.put("bodytext", "");
                values.put("attachedFileName", tempExcelFileName.getName());

                final ViewBasedDisplayDialog dlg = new ViewBasedDisplayDialog((Frame) UIRegistry.getTopWindow(),
                        "SystemSetup", "SendMail", null, getResourceString("SEND_MAIL_TITLE"),
                        getResourceString("SEND_BTN"), null, // className,
                        null, // idFieldName,
                        true, // isEdit,
                        0);
                dlg.setData(values);
                dlg.setModal(true);
                dlg.setVisible(true);
                if (dlg.getBtnPressed() == ViewBasedDisplayIFace.OK_BTN) {
                    dlg.getMultiView().getDataFromUI();

                    //System.out.println("["+values.get("bodytext")+"]");

                    TableViewObj tblViewObj = (TableViewObj) viewable;
                    File excelFile = TableModel2Excel.convertToExcel(tempExcelFileName,
                            getResourceString("CollectionObject"), tblViewObj.getTable().getModel());
                    StringBuilder sb = TableModel2Excel.convertToHTML(getResourceString("CollectionObject"),
                            tblViewObj.getTable().getModel());

                    //EMailHelper.setDebugging(true);
                    String text = values.get("bodytext").replace("\n", "<br>") + "<BR><BR>" + sb.toString();

                    // XXX need to move the invokdeLater into the UIRegistry
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            UIRegistry.displayLocalizedStatusBarText("SENDING_EMAIL");
                        }
                    });

                    if (sendEMail) {
                        final EMailHelper.ErrorType status = EMailHelper.sendMsg(emailPrefs.get("servername"),
                                emailPrefs.get("username"), Encryption.decrypt(emailPrefs.get("password")),
                                emailPrefs.get("email"), values.get("to"), values.get("subject"), text,
                                EMailHelper.HTML_TEXT, emailPrefs.get("port"), emailPrefs.get("security"),
                                excelFile);
                        if (status != EMailHelper.ErrorType.Cancel) {
                            SwingUtilities.invokeLater(new Runnable() {
                                public void run() {
                                    UIRegistry.displayLocalizedStatusBarText(
                                            status == EMailHelper.ErrorType.Error ? "EMAIL_SENT_ERROR"
                                                    : "EMAIL_SENT_OK");
                                }
                            });
                        }
                    }
                }
            }
        }
    } else {
        log.error("Why doesn't the current SubPane have a main FormViewObj?");
    }
}

From source file:de.cebitec.readXplorer.differentialExpression.plot.DeSeq2GraphicsTopComponent.java

private void plotButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_plotButtonActionPerformed
    try {//from   www  .j a  v a  2s.co m
        messages.setText("");
        plotButton.setEnabled(false);
        saveButton.setEnabled(false);
        DeSeq2AnalysisHandler.Plot selectedPlot = (DeSeq2AnalysisHandler.Plot) plotType.getSelectedItem();
        plotDescriptionArea.setVisible(true);
        if (!SVGCanvasActive) {
            plotPanel.remove(chartPanel);
            plotPanel.add(svgCanvas, BorderLayout.CENTER);
            plotPanel.updateUI();
            SVGCanvasActive = true;
        }
        currentlyDisplayed = ((DeSeq2AnalysisHandler) analysisHandler).plot(selectedPlot);
        svgCanvas.setURI(currentlyDisplayed.toURI().toString());
        svgCanvas.setVisible(true);
        svgCanvas.repaint();

        plotDescriptionArea.repaint();
    } catch (IOException ex) {
        Date currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "{0}: " + ex.getMessage(),
                currentTimestamp);
        JOptionPane.showMessageDialog(null, "Can't create the temporary svg file!", "Gnu R Error",
                JOptionPane.WARNING_MESSAGE);
    } catch (GnuR.PackageNotLoadableException ex) {
        Date currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "{0}: " + ex.getMessage(),
                currentTimestamp);
        JOptionPane.showMessageDialog(null, ex.getMessage(), "Gnu R Error", JOptionPane.WARNING_MESSAGE);
    }
}

From source file:ru.develgame.jflickrorganizer.LoginForm.java

private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOKActionPerformed
    if (jCheckBoxOfflineMode.isSelected()) {
        if (jTextFieldLogin.getText().isEmpty()) {
            // TODO
            return;
        }//  www . j av  a  2 s.c  o  m

        String pass = new String(jPassword.getPassword());
        if (pass.isEmpty()) {
            // TODO
            return;
        }

        User userByName = userRepository.findByName(jTextFieldLogin.getText());
        if (userByName == null) {
            // TODO
            return;
        }

        if (userByName.getPass() == null || userByName.getPass().isEmpty()) {
            // TODO
            return;
        }

        String hashedPass = "";
        try {
            MessageDigest m = MessageDigest.getInstance("SHA-1");
            m.reset();
            m.update(pass.getBytes());
            hashedPass = new String(m.digest());
        } catch (NoSuchAlgorithmException ex) {
            // TODO
            return;
        }

        if (!hashedPass.equals(userByName.getPass())) {
            // TODO
            return;
        }

        authorizer.setOfflineMode(true);
        authorizer.setUser(userByName);
    } else {
        if (jTextFieldToken.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this,
                    LocaleMessages.getMessage("LoginForm.Warning.TokenCannotBeEmpty"),
                    LocaleMessages.getMessage("WarningTitle"), JOptionPane.WARNING_MESSAGE);

            return;
        }

        if (!authorizer.doAuthorize(jTextFieldToken.getText())) {
            JOptionPane.showMessageDialog(this,
                    LocaleMessages.getMessage("LoginForm.Error.AuthorizationFailed"),
                    LocaleMessages.getMessage("ErrorTitle"), JOptionPane.ERROR_MESSAGE);

            return;
        }

        User userByName = userRepository.findByName(authorizer.getAuth().getUser().getUsername());
        if (userByName == null) {
            userByName = new User(authorizer.getAuth().getUser().getUsername());
            userRepository.save(userByName);
        }

        authorizer.setUser(userByName);
    }

    getMainForm().setVisible(true);

    this.setVisible(false);
    this.dispose();
}

From source file:userinterface.InventoryRole.InventoryWorkAreaJPanel.java

private void processReqBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_processReqBtnActionPerformed
    // TODO add your handling code here:
    int selectedRow = inventoryTable.getSelectedRow();

    if (selectedRow < 0) {
        JOptionPane.showMessageDialog(null, "please select a row!", "warning", JOptionPane.WARNING_MESSAGE);
        return;//from w  w w. j  a  v  a 2 s.  c  o m
    } else {
        DoctorWorkRequest request = (DoctorWorkRequest) inventoryTable.getValueAt(selectedRow, 2);
        int quantity = request.getQuantity();
        String bGroup = request.getBloodGroup();
        int a = enterprise.getHash().get("A+");
        int b = enterprise.getHash().get("A-");
        int c = enterprise.getHash().get("B+");
        int d = enterprise.getHash().get("B-");
        int e = enterprise.getHash().get("AB+");
        int f = enterprise.getHash().get("AB-");
        int g = enterprise.getHash().get("O+");
        int h = enterprise.getHash().get("O-");

        if (bGroup.equalsIgnoreCase("A+")) {
            if (a <= 0 && a < quantity) {
                JOptionPane.showMessageDialog(this, "Required blood group is not available ", "Warning",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                int a1 = a - quantity;
                enterprise.getHash().put("A+", a1);
                aPosTextField.setText((String.valueOf(a1)));
            }

        } else if (bGroup.equalsIgnoreCase("A-")) {
            if (b <= 0 && b < quantity) {
                JOptionPane.showMessageDialog(this, "Required blood group is not available ", "Warning",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                int b1 = b - quantity;
                enterprise.getHash().put("A-", b1);
                aNeTextField.setText((String.valueOf(b1)));
            }

        } else if (bGroup.equalsIgnoreCase("B+")) {
            if (c <= 0 && c < quantity) {
                JOptionPane.showMessageDialog(this, "Required blood group is not available ", "Warning",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                int c1 = c - quantity;
                enterprise.getHash().put("B+", c1);
                bPosTextField.setText((String.valueOf(c1)));
            }

        } else if (bGroup.equalsIgnoreCase("B-")) {
            if (d <= 0 && d < quantity) {
                JOptionPane.showMessageDialog(this, "Required blood group is not available ", "Warning",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                int d1 = d - quantity;
                enterprise.getHash().put("B-", d1);
                bNeTextField.setText((String.valueOf(d1)));
            }

        } else if (bGroup.equalsIgnoreCase("AB+")) {
            if (e <= 0 && e < quantity) {
                JOptionPane.showMessageDialog(this, "Required blood group is not available ", "Warning",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                int e1 = e - quantity;
                enterprise.getHash().put("AB+", e1);
                abPosTextField.setText((String.valueOf(e1)));
            }

        } else if (bGroup.equalsIgnoreCase("AB-")) {
            if (f <= 0 && f < quantity) {
                JOptionPane.showMessageDialog(this, "Required blood group is not available ", "Warning",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                int f1 = f - quantity;
                enterprise.getHash().put("AB-", f1);
                abNeTextField.setText((String.valueOf(f1)));
            }

        } else if (bGroup.equalsIgnoreCase("O+")) {
            if (g <= 0 && g < quantity) {
                JOptionPane.showMessageDialog(this, "Required blood group is not available ", "Warning",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                int g1 = g - quantity;
                enterprise.getHash().put("O+", g1);
                oPosTextField.setText((String.valueOf(g1)));
            }

        } else if (bGroup.equalsIgnoreCase("O-")) {
            if (h <= 0 && h < quantity) {
                JOptionPane.showMessageDialog(this, "Required blood group is not available ", "Warning",
                        JOptionPane.WARNING_MESSAGE);
            } else {
                int h1 = h - quantity;
                enterprise.getHash().put("O-", h1);
                oNeTextField.setText((String.valueOf(h1)));
            }

        }
    }
}

From source file:misc.TextBatchPrintingDemo.java

/**
 * Create and display the main application frame.
 *//*  w  w  w.java  2 s  . com*/
void createAndShowGUI() {
    messageArea = new JLabel(defaultMessage);

    selectedPages = new JList(new DefaultListModel());
    selectedPages.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    selectedPages.addListSelectionListener(this);

    setPage(homePage);

    JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(pageItem),
            new JScrollPane(selectedPages));

    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic(KeyEvent.VK_F);

    /** Menu item and keyboard shortcuts for the "add page" command.  */
    fileMenu.add(createMenuItem(new AbstractAction("Add Page") {
        public void actionPerformed(ActionEvent e) {
            DefaultListModel pages = (DefaultListModel) selectedPages.getModel();
            pages.addElement(pageItem);
            selectedPages.setSelectedIndex(pages.getSize() - 1);
        }
    }, KeyEvent.VK_A, KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.ALT_MASK)));

    /** Menu item and keyboard shortcuts for the "print selected" command.*/
    fileMenu.add(createMenuItem(new AbstractAction("Print Selected") {
        public void actionPerformed(ActionEvent e) {
            printSelectedPages();
        }
    }, KeyEvent.VK_P, KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.ALT_MASK)));

    /** Menu item and keyboard shortcuts for the "clear selected" command.*/
    fileMenu.add(createMenuItem(new AbstractAction("Clear Selected") {
        public void actionPerformed(ActionEvent e) {
            DefaultListModel pages = (DefaultListModel) selectedPages.getModel();
            pages.removeAllElements();
        }
    }, KeyEvent.VK_C, KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.ALT_MASK)));

    fileMenu.addSeparator();

    /** Menu item and keyboard shortcuts for the "home page" command.  */
    fileMenu.add(createMenuItem(new AbstractAction("Home Page") {
        public void actionPerformed(ActionEvent e) {
            setPage(homePage);
        }
    }, KeyEvent.VK_H, KeyStroke.getKeyStroke(KeyEvent.VK_H, ActionEvent.ALT_MASK)));

    /** Menu item and keyboard shortcuts for the "quit" command.  */
    fileMenu.add(createMenuItem(new AbstractAction("Quit") {
        public void actionPerformed(ActionEvent e) {
            for (Window w : Window.getWindows()) {
                w.dispose();
            }
        }
    }, KeyEvent.VK_A, KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.ALT_MASK)));

    JMenuBar menuBar = new JMenuBar();
    menuBar.add(fileMenu);

    JPanel contentPane = new JPanel();
    contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
    contentPane.add(pane);
    contentPane.add(messageArea);

    JFrame frame = new JFrame("Text Batch Printing Demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setJMenuBar(menuBar);
    frame.setContentPane(contentPane);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    if (printService == null) {
        // Actual printing is not possible, issue a warning message.
        JOptionPane.showMessageDialog(frame, "No default print service", "Print Service Alert",
                JOptionPane.WARNING_MESSAGE);
    }
}

From source file:DialogDemo.java

private JPanel createIconDialogBox() {
    JButton showItButton = null;//  w w  w.  j  a  va2  s  . c  o m

    final int numButtons = 6;
    JRadioButton[] radioButtons = new JRadioButton[numButtons];
    final ButtonGroup group = new ButtonGroup();

    final String plainCommand = "plain";
    final String infoCommand = "info";
    final String questionCommand = "question";
    final String errorCommand = "error";
    final String warningCommand = "warning";
    final String customCommand = "custom";

    radioButtons[0] = new JRadioButton("Plain (no icon)");
    radioButtons[0].setActionCommand(plainCommand);

    radioButtons[1] = new JRadioButton("Information icon");
    radioButtons[1].setActionCommand(infoCommand);

    radioButtons[2] = new JRadioButton("Question icon");
    radioButtons[2].setActionCommand(questionCommand);

    radioButtons[3] = new JRadioButton("Error icon");
    radioButtons[3].setActionCommand(errorCommand);

    radioButtons[4] = new JRadioButton("Warning icon");
    radioButtons[4].setActionCommand(warningCommand);

    radioButtons[5] = new JRadioButton("Custom icon");
    radioButtons[5].setActionCommand(customCommand);

    for (int i = 0; i < numButtons; i++) {
        group.add(radioButtons[i]);
    }
    radioButtons[0].setSelected(true);

    showItButton = new JButton("Show it!");
    showItButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String command = group.getSelection().getActionCommand();

            // no icon
            if (command == plainCommand) {
                JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green.", "A plain message",
                        JOptionPane.PLAIN_MESSAGE);
                // information icon
            } else if (command == infoCommand) {
                JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green.",
                        "Inane informational dialog", JOptionPane.INFORMATION_MESSAGE);

                // XXX: It doesn't make sense to make a question with
                // XXX: only one button.
                // XXX: See "Yes/No (but not in those words)" for a better solution.
                // question icon
            } else if (command == questionCommand) {
                JOptionPane.showMessageDialog(frame,
                        "You shouldn't use a message dialog " + "(like this)\n" + "for a question, OK?",
                        "Inane question", JOptionPane.QUESTION_MESSAGE);
                // error icon
            } else if (command == errorCommand) {
                JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green.", "Inane error",
                        JOptionPane.ERROR_MESSAGE);
                // warning icon
            } else if (command == warningCommand) {
                JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green.", "Inane warning",
                        JOptionPane.WARNING_MESSAGE);
                // custom icon
            } else if (command == customCommand) {
                JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green.", "Inane custom dialog",
                        JOptionPane.INFORMATION_MESSAGE, icon);
            }
        }
    });

    return create2ColPane(iconDesc + ":", radioButtons, showItButton);
}

From source file:AltiConsole.AltiConsoleMainScreen.java

/**
 * Constructs main screen of the application.
 * /*from www .  ja  v  a  2  s .  c  om*/
 * @param title
 *            the frame title.
 */
public AltiConsoleMainScreen(final String title) {

    super(title);
    trans = Application.getTranslator();

    // //////// Menu code starts her //////////////
    // File
    fileMenu = new JMenu();
    fileMenu.setText(trans.get("AltiConsoleMainScreen.File"));

    // Load data
    loadDataMenuItem = new JMenuItem();
    loadDataMenuItem.setText(trans.get("AltiConsoleMainScreen.RetrieveFlightData"));
    loadDataMenuItem.setActionCommand("RETRIEVE_FLIGHT");
    loadDataMenuItem.addActionListener(this);

    eraseAllDataMenuItem = new JMenuItem();
    eraseAllDataMenuItem.setText(trans.get("AltiConsoleMainScreen.EraseFlightData"));
    eraseAllDataMenuItem.setActionCommand("ERASE_FLIGHT");
    eraseAllDataMenuItem.addActionListener(this);

    // Save as
    saveASMenuItem = new JMenuItem();
    saveASMenuItem.setText(trans.get("AltiConsoleMainScreen.saveFlightData"));
    saveASMenuItem.setActionCommand("SAVE_FLIGHT");
    saveASMenuItem.addActionListener(this);

    // Exit
    exitMenuItem = new JMenuItem();
    exitMenuItem.setText(trans.get("AltiConsoleMainScreen.Exit"));
    exitMenuItem.setActionCommand("EXIT");
    exitMenuItem.addActionListener(this);

    fileMenu.add(saveASMenuItem);

    fileMenu.add(loadDataMenuItem);
    fileMenu.add(eraseAllDataMenuItem);
    fileMenu.add(exitMenuItem);

    // Option menu
    optionMenu = new JMenu(trans.get("AltiConsoleMainScreen.Option"));
    preferencesMenuItem = new JMenuItem(trans.get("AltiConsoleMainScreen.Preferences"));
    preferencesMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("pref\n");
            Preferences.showPreferences(AltiConsoleMainScreen.this);
            //LicenseDialog.showPreferences(AltiConsoleMainScreen.this);
            System.out.println("change units\n");
            String Units;
            System.out.println(UserPref.getAppUnits());
            if (Utils.equals(UserPref.getAppUnits(), "Unit.Metrics"))
                Units = trans.get("Unit.Metrics");
            else
                Units = trans.get("Unit.Imperial");

            chart.getXYPlot().getRangeAxis()
                    .setLabel(trans.get("AltiConsoleMainScreen.altitude") + " (" + Units + ")");
            if (Serial.getConnected()) {
                RetrievingFlight();
            }

        }
    });

    optionMenu.add(preferencesMenuItem);

    // Configuration menu
    altiConfigMenu = new JMenu(trans.get("AltiConsoleMainScreen.ConfigAltimeter"));

    retrieveAltiConfigMenuItem = new JMenuItem(trans.get("AltiConsoleMainScreen.RetrieveAltiConfig"));
    retrieveAltiConfigMenuItem.setActionCommand("RETRIEVE_ALTI_CFG");
    retrieveAltiConfigMenuItem.addActionListener(this);
    altiConfigMenu.add(retrieveAltiConfigMenuItem);

    uploadFirmwareMenuItem = new JMenuItem(trans.get("AltiConsoleMainScreen.UploadFirmware"));

    uploadFirmwareMenuItem.setActionCommand("UPLOAD_FIRMWARE");
    uploadFirmwareMenuItem.addActionListener(this);
    altiConfigMenu.add(uploadFirmwareMenuItem);

    // Help
    helpMenu = new JMenu(trans.get("AltiConsoleMainScreen.Help"));
    jJMenuBar = new JMenuBar();

    // Manual
    onLineHelpMenuItem = new JMenuItem(trans.get("AltiConsoleMainScreen.onLineHelp"));
    onLineHelpMenuItem.setActionCommand("ON_LINE_HELP");
    onLineHelpMenuItem.addActionListener(this);

    // license
    licenseMenuItem = new JMenuItem(trans.get("AltiConsoleMainScreen.license"));
    licenseMenuItem.setActionCommand("LICENSE");
    licenseMenuItem.addActionListener(this);

    // AboutScreen
    aboutMenuItem = new JMenuItem();
    aboutMenuItem.setText(trans.get("AltiConsoleMainScreen.About"));
    aboutMenuItem.setActionCommand("ABOUT");
    aboutMenuItem.addActionListener(this);

    helpMenu.add(onLineHelpMenuItem);
    helpMenu.add(licenseMenuItem);
    helpMenu.add(aboutMenuItem);

    jJMenuBar.add(fileMenu);
    jJMenuBar.add(optionMenu);
    jJMenuBar.add(altiConfigMenu);
    jJMenuBar.add(helpMenu);
    this.setJMenuBar(jJMenuBar);

    // ///// end of Menu code

    // Button
    retrieveFlights = new JButton();
    retrieveFlights.setText(trans.get("AltiConsoleMainScreen.RetrieveFlights"));
    retrieveFlights.setActionCommand("RETRIEVE_FLIGHT");
    retrieveFlights.addActionListener(this);
    retrieveFlights.setToolTipText(trans.get("AltiConsoleMainScreen.ttipRetrieveFlight"));

    // combo serial rate
    String[] serialRateStrings = { "300", "1200", "2400", "4800", "9600", "14400", "19200", "28800", "38400",
            "57600", "115200" };

    serialRatesLabel = new JLabel(trans.get("AltiConsoleMainScreen.comPortSpeed") + " ");
    serialRates = new JComboBox();
    System.out.println(UserPref.getDefComSpeed() + "\n");
    for (int i = 0; i < serialRateStrings.length; i++) {
        serialRates.addItem(serialRateStrings[i]);

        if (Utils.equals(UserPref.getDefComSpeed(), serialRateStrings[i])) {
            serialRates.setSelectedIndex(i);
        }
    }
    serialRates.setToolTipText(trans.get("AltiConsoleMainScreen.ttipChoosePortSpeed"));

    comPortsLabel = new JLabel(trans.get("AltiConsoleMainScreen.port") + " ");
    comPorts = new JComboBox();

    comPorts.setActionCommand("comPorts");
    comPorts.addActionListener(this);
    comPorts.setToolTipText(trans.get("AltiConsoleMainScreen.ttipChooseAltiport"));
    listData = new DefaultListModel();

    flightList = new JXList(listData);
    flightList.addListSelectionListener(new ValueReporter());

    JPanel TopPanelLeft = new JPanel();
    TopPanelLeft.setLayout(new BorderLayout());
    TopPanelLeft.add(comPortsLabel, BorderLayout.WEST);
    TopPanelLeft.add(comPorts, BorderLayout.EAST);

    JPanel TopPanelMiddle = new JPanel();
    TopPanelMiddle.setLayout(new BorderLayout());
    TopPanelMiddle.add(retrieveFlights, BorderLayout.WEST);

    JPanel TopPanelRight = new JPanel();
    TopPanelRight.setLayout(new BorderLayout());
    TopPanelRight.add(serialRatesLabel, BorderLayout.WEST);
    TopPanelRight.add(serialRates, BorderLayout.EAST);

    JPanel TopPanel = new JPanel();
    TopPanel.setLayout(new BorderLayout());

    TopPanel.add(TopPanelRight, BorderLayout.EAST);
    TopPanel.add(TopPanelMiddle, BorderLayout.CENTER);
    TopPanel.add(TopPanelLeft, BorderLayout.WEST);
    JPanel MiddlePanel = new JPanel();
    MiddlePanel.setLayout(new BorderLayout());

    MiddlePanel.add(TopPanel, BorderLayout.NORTH);
    MiddlePanel.add(flightList, BorderLayout.WEST);

    String Units;
    if (Utils.equals(UserPref.getAppUnits(), "Unit.Metrics"))
        Units = trans.get("Unit.Metrics");
    else
        Units = trans.get("Unit.Imperial");

    chart = ChartFactory.createXYLineChart(trans.get("AltiConsoleMainScreen.Title"),
            trans.get("AltiConsoleMainScreen.time"),
            trans.get("AltiConsoleMainScreen.altitude") + " (" + Units + ")", null);

    chart.setBackgroundPaint(Color.white);
    System.out.println(chart.getSubtitle(0));

    this.plot = chart.getXYPlot();
    this.plot.setBackgroundPaint(Color.lightGray);
    this.plot.setDomainGridlinePaint(Color.white);
    this.plot.setRangeGridlinePaint(Color.white);

    final ValueAxis axis = this.plot.getDomainAxis();
    axis.setAutoRange(true);

    final NumberAxis rangeAxis2 = new NumberAxis("Range Axis 2");
    rangeAxis2.setAutoRangeIncludesZero(false);

    final ChartPanel chartPanel = new ChartPanel(chart);

    MiddlePanel.add(chartPanel, BorderLayout.CENTER);

    JPanel InfoPanel = new JPanel(new MigLayout("fill"));
    InfoPanel.add(new JLabel(trans.get("AltiConsoleMainScreen.ApogeeAltitude")), "gapright para");
    apogeeAltitudeLabel = new JLabel();
    InfoPanel.add(apogeeAltitudeLabel, "growx");
    InfoPanel.add(new JLabel(trans.get("AltiConsoleMainScreen.MainAltitude")), "gapright para");
    mainAltitudeLabel = new JLabel();
    InfoPanel.add(mainAltitudeLabel, "growx");
    flightNbrLabel = new JLabel();

    InfoPanel.add(new JLabel(trans.get("AltiConsoleMainScreen.NbrOfPoint")), "growx");
    nbrPointLabel = new JLabel();
    InfoPanel.add(nbrPointLabel, "wrap rel,growx");

    txtLog = new JTextArea(5, 70);
    txtLog.setEditable(false);
    txtLog.setAutoscrolls(true);

    scrollPane = new JScrollPane(txtLog);
    scrollPane.setAutoscrolls(true);
    // BottomPanel.add(scrollPane, BorderLayout.WEST);
    InfoPanel.add(scrollPane, "span");
    // MiddlePanel.add(BottomPanel, BorderLayout.SOUTH);
    MiddlePanel.add(InfoPanel, BorderLayout.SOUTH);
    setContentPane(MiddlePanel);
    try {
        try {
            Serial = new AltimeterSerial(this);

            Serial.searchForPorts();
        } catch (UnsatisfiedLinkError e) {
            System.out.println("USB Library rxtxSerial.dll Not Found");
            System.out.println("Exception:" + e.toString() + ":" + e.getMessage());
            System.out.println(e.toString());
            JOptionPane.showMessageDialog(null,
                    "You must copy the appropriate rxtxSerial.dll \n "
                            + "to your local 32 bit or 64 bitjava JRE installation\n\n"
                            + " .../arduino-1.0.1-windows/arduino-1.0.1/rxtxSerial.dll\n"
                            + "to\n C:/Program Files (x86)/Java/jre7/bin/rxtxSerial.dll\n"
                            + "also right click Properties->Unblock",
                    trans.get("AltiConsoleMainScreen.InstallationProblem"), JOptionPane.WARNING_MESSAGE);
        }
    } catch (NoClassDefFoundError e) {
        System.out.println("Missing RXTXcomm.jar in java installation");
        System.out.println("Exception:" + e.toString() + ":" + e.getMessage());
        System.out.println(e.toString());
        JOptionPane.showMessageDialog(null,
                "You must copy RXTXcomm.jar from the Arduino software\n "
                        + "to your local 32 bit java JRE installation\n\n"
                        + " .../arduino-1.0.1-windows/arduino-1.0.1/lib/RXTXcomm.jar\n"
                        + "to\n C:/Program Files (x86)/Java/jre7/lib/ext/RXTXcomm.jar\n"
                        + "also right click Properties->Unblock",
                trans.get("AltiConsoleMainScreen.InstallationProblem"), JOptionPane.WARNING_MESSAGE);
    }
}