我正在使用JOptionPane来显示错误消息,但是当我在错误消息上单击“确定”时,它不会关闭消息

时间:2017-09-10 22:34:09

标签: java swing joptionpane

我正在制作一个单位转换器并遇到了JOptionPane.showMessageDialog的问题代码已经完成,应该运行正常。

如果将两个转换单元放在同一个单元上,转换器会显示一个消息对话框。当弹出消息窗口并显示消息时,单击确定按钮。单击“确定”按钮时,它不会退出消息对话框。我从这个转换器的不同更长版本复制了它的代码行,它可以正常工作。如果您对如何更好地进行数学计算有任何建议,请告诉我。我仍然是编程和Java的初学者。任何帮助表示赞赏。

 package V3Converter;


import java.awt.Toolkit;
import java.math.BigInteger;
import java.util.HashMap;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;

/**
*
* @author Anthony Tennenbaum
*/
public class v3Converter extends javax.swing.JFrame {


    //constant type double arrays filled in order of: centimeter,feet,inche,kilometer,mile,millimeter,meter,yard
    final double[] TO_CENTM = {1,30.48,2.54,100000,160935,0.1,100,91.44};
    final double[] TO_FEET = {0.032808399,1,0.083333333334,3280.839895,5280.019685,0.0032808399,3.280839895,3};
    final double[] TO_INCHE ={0.3937007874,12,1,39370.07874,63360.23622, 0.0393700787,39.37007874,36} ;
    final double[] TO_KILOM = { 0.00001,0.0003048, } ;
    final double[] TO_MILE = {};
    final double[] TO_MILIM = {};
    final double[] TO_METER = {0.01,0.3048,0.0254,0.001,1609.35,0.001,1,0.9144}; 
    final double[] TO_YARD = {0.010936133,0.3333333333,0.0277777778,1093.6132983,1760.0065617,1760.0065617,1};

    //making a String array
    final String[] UNIT_NAME = {"Centimeters", "Feet", "Inches", "Kilometers", "Miles", "Millimeters", "Meters", "Yards"};a



/**
 * Creates new form Converter
 */
public v3Converter() {
    initComponents();
    setIcon();  //sets the icon image for the jFrame
    setSize(350,225);  //set the starting size of frame
    setLocationRelativeTo(null);     //on startup centers the frame
    getContentPane().setBackground(java.awt.Color.BLACK);
    comboBoxFrom.setSelectedIndex(0);    //comboBox starts at index 0(first item in list) -1 puts box empty
    comboBoxTo.setSelectedIndex(0);

}


@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    btnConvert = new javax.swing.JButton();
    comboBoxFrom = new javax.swing.JComboBox<>();
    comboBoxTo = new javax.swing.JComboBox<>();
    txtField1 = new javax.swing.JTextField();
    btnReset = new javax.swing.JButton();
    btnExit = new javax.swing.JButton();
    lblConvertTo = new javax.swing.JLabel();
    lblConvertFrom = new javax.swing.JLabel();
    pnlAnswer = new javax.swing.JPanel();
    lblAnswer = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Unit Converter");
    setFont(new java.awt.Font("Copperplate Gothic Light", 1, 14)); // NOI18N
    setResizable(false);

    btnConvert.setBackground(new java.awt.Color(204, 0, 0));
    btnConvert.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
    btnConvert.setForeground(new java.awt.Color(0, 204, 0));
    btnConvert.setText("Convert");
    btnConvert.setActionCommand("Convert To");
    btnConvert.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnConvertActionPerformed(evt);
        }
    });

    comboBoxFrom.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Choose One..", "Length Units", "Time Units" }));
    comboBoxFrom.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            comboBoxFromActionPerformed(evt);
        }
    });

    comboBoxTo.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Choose One..", " " }));
    comboBoxTo.setToolTipText("");
    comboBoxTo.setEnabled(false);
    comboBoxTo.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            comboBoxToActionPerformed(evt);
        }
    });

    txtField1.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
    txtField1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            txtField1ActionPerformed(evt);
        }
    });

    btnReset.setBackground(new java.awt.Color(0, 204, 0));
    btnReset.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
    btnReset.setForeground(new java.awt.Color(204, 0, 0));
    btnReset.setText("Reset");
    btnReset.setActionCommand("Convert To");
    btnReset.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnResetActionPerformed(evt);
        }
    });

    btnExit.setBackground(new java.awt.Color(0, 0, 204));
    btnExit.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
    btnExit.setForeground(new java.awt.Color(204, 0, 0));
    btnExit.setText("Exit");
    btnExit.setActionCommand("Convert To");
    btnExit.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnExitActionPerformed(evt);
        }
    });

    lblConvertTo.setFont(new java.awt.Font("Copperplate Gothic Light", 1, 11)); // NOI18N
    lblConvertTo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    lblConvertTo.setText("Convert to");

    lblConvertFrom.setFont(new java.awt.Font("Copperplate Gothic Light", 1, 11)); // NOI18N
    lblConvertFrom.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    lblConvertFrom.setText("Convert From");

    pnlAnswer.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2));

    lblAnswer.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
    lblAnswer.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

    javax.swing.GroupLayout pnlAnswerLayout = new javax.swing.GroupLayout(pnlAnswer);
    pnlAnswer.setLayout(pnlAnswerLayout);
    pnlAnswerLayout.setHorizontalGroup(
        pnlAnswerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(pnlAnswerLayout.createSequentialGroup()
            .addComponent(lblAnswer, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(0, 0, Short.MAX_VALUE))
    );
    pnlAnswerLayout.setVerticalGroup(
        pnlAnswerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlAnswerLayout.createSequentialGroup()
            .addGap(0, 0, Short.MAX_VALUE)
            .addComponent(lblAnswer, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(266, 266, 266)
                    .addComponent(btnExit))
                .addGroup(layout.createSequentialGroup()
                    .addGap(22, 22, 22)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnConvert)
                                .addGap(45, 45, 45)
                                .addComponent(btnReset)
                                .addGap(196, 196, 196))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(pnlAnswer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(comboBoxTo, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addComponent(lblConvertTo, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(lblConvertFrom, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtField1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(comboBoxFrom, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE))))))
            .addContainerGap(421, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(lblConvertFrom)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(comboBoxFrom, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(txtField1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(btnConvert)
                .addComponent(btnReset)
                .addComponent(btnExit))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(pnlAnswer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(lblConvertTo))
                .addComponent(comboBoxTo, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap(324, Short.MAX_VALUE))
    );

    pack();
    setLocationRelativeTo(null);
}// </editor-fold>                        

private void comboBoxFromActionPerformed(java.awt.event.ActionEvent evt) {                                             

    //String lengthUnits[] = {"Centimeters", "Feet", "Inches", "Kilometers", "Light Years", "Miles", "Millimeters", "Meters", "Yards" };  //makes an array called lengthUnits then populates it
    String timeUnits[] = {"Hours", "Milliseconds", "Minutes", "Seconds"};
    if(comboBoxFrom.getSelectedItem().equals("Length Units")){   //if true then 
        comboBoxTo.setEnabled(true);  //set the comboBoxTo to be activated
        //DefaultComboBoxModel time = new DefaultComboBoxModel(timeUnits); 
        comboBoxFrom.setModel( new DefaultComboBoxModel( UNIT_NAME ) );  //sets the model of comboBoxFrom to array lengthUnits
        comboBoxTo.setModel( new DefaultComboBoxModel( UNIT_NAME) );    //sets the model of comboBoxTo to array lengthUnits
    }
    else if(comboBoxFrom.getSelectedItem().equals("Time Units")){
        comboBoxTo.setEnabled(true);   //set the comboBoxTo to be activated
        //DefaultComboBoxModel time = new DefaultComboBoxModel(timeUnits);  //makes a new model and fills it from the array timeUnits and will link the 2 comboBox's
        comboBoxFrom.setModel( new DefaultComboBoxModel( timeUnits ) );  //also makes a new model and fills it from the array timeUnits
        comboBoxTo.setModel( new DefaultComboBoxModel( timeUnits ) );   //but doesn't link the oomboBox's

    }

}                                            

private void comboBoxToActionPerformed(java.awt.event.ActionEvent evt) {                                           

}                                          

private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {                                         
    String comboStart[] = {"Choose one..", "Length Units", "Time Units"};
    lblAnswer.setText(null);   //making the lable clear
    txtField1.setText(null);       //making the textField clear
    DefaultComboBoxModel reset = new DefaultComboBoxModel(comboStart);
    comboBoxFrom.setModel(reset);  //set the model of the comboBoxFrom to the default setting
    comboBoxTo.setModel(reset);
    comboBoxFrom.setSelectedIndex(0); // starts the comboBox at index 0. type -1 to start it empty
    comboBoxTo.setSelectedIndex(0);
    comboBoxTo.setEnabled(false);   //deactivates the combBoxTo
    lblAnswer.setText(null);   //sets the lable or where answer displays, back to empty


}                                        

private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {                                        

    System.exit(0);    //closes the program
}                                       

private void btnConvertActionPerformed(java.awt.event.ActionEvent evt) {                                           

    String userInput = txtField1.getText(); //userInput equals to whatever the user typed in txtField1

    try{
        Double.parseDouble(userInput); //checks to see if the userInput from the txtField1 is an integer if not the catch takes control

        for(String s: UNIT_NAME){
            if(comboBoxFrom.getSelectedItem().equals(comboBoxTo.getSelectedItem())){
                JOptionPane.showMessageDialog(null, "Cannot convert to the same unit type.", "Um, You Forgot Something!!", JOptionPane.INFORMATION_MESSAGE);
            }
            else if((comboBoxFrom.getSelectedItem().equals(s)) && comboBoxTo.getSelectedItem().equals("Centimeters")){
                double answer = (Double.parseDouble(userInput) * TO_CENTM[comboBoxFrom.getSelectedIndex()]) ;   //converts userInput into a type double then makes the unit conversion
                lblAnswer.setText(String.valueOf(answer));
            }
            else if((comboBoxFrom.getSelectedItem().equals(s)) && comboBoxTo.getSelectedItem().equals("Feet")){
                double answer = (Double.parseDouble(userInput) * TO_FEET[comboBoxFrom.getSelectedIndex()]) ;   //converts userInput into a type double then makes the unit conversion
                lblAnswer.setText(String.valueOf(answer)); 
            }
            else if((comboBoxFrom.getSelectedItem().equals(s)) && comboBoxTo.getSelectedItem().equals("Inches")){
                double answer = (Double.parseDouble(userInput) * TO_INCHE[comboBoxFrom.getSelectedIndex()]) ;   //converts userInput into a type double then makes the unit conversion
                lblAnswer.setText(String.valueOf(answer)); 
            }
            else if((comboBoxFrom.getSelectedItem().equals(s)) && comboBoxTo.getSelectedItem().equals("Kilometers")){
                double answer = (Double.parseDouble(userInput) * TO_KILOM[comboBoxFrom.getSelectedIndex()]) ;   //converts userInput into a type double then makes the unit conversion
                lblAnswer.setText(String.valueOf(answer)); 
            }
            else if((comboBoxFrom.getSelectedItem().equals(s)) && comboBoxTo.getSelectedItem().equals("Miles")){
                double answer = (Double.parseDouble(userInput) * TO_MILE[comboBoxFrom.getSelectedIndex()]) ;   //converts userInput into a type double then makes the unit conversion
                lblAnswer.setText(String.valueOf(answer)); 
            }
            else if((comboBoxFrom.getSelectedItem().equals(s)) && comboBoxTo.getSelectedItem().equals("Millimeters")){
                double answer = (Double.parseDouble(userInput) * TO_MILIM[comboBoxFrom.getSelectedIndex()]) ;   //converts userInput into a type double then makes the unit conversion
                lblAnswer.setText(String.valueOf(answer)); 
            }
            else if((comboBoxFrom.getSelectedItem().equals(s)) && comboBoxTo.getSelectedItem().equals("Meters")){
                double answer = (Double.parseDouble(userInput) * TO_METER[comboBoxFrom.getSelectedIndex()]) ;   //converts userInput into a type double then makes the unit conversion
                lblAnswer.setText(String.valueOf(answer)); 
            }
            else if((comboBoxFrom.getSelectedItem().equals(s)) && comboBoxTo.getSelectedItem().equals("Yards")){
                double answer = (Double.parseDouble(userInput) * TO_YARD[comboBoxFrom.getSelectedIndex()]) ;   //converts userInput into a type double then makes the unit conversion
                lblAnswer.setText(String.valueOf(answer)); 
            }
        }                    
    }
    catch(NumberFormatException e){
       JOptionPane.showMessageDialog(this, "You must type a Number", "HEY IDIOT!!", JOptionPane.INFORMATION_MESSAGE); 
    }
}                                          

private void txtField1ActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
}                                         

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(v3Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(v3Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(v3Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(v3Converter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>
    //</editor-fold>
    //</editor-fold>
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new v3Converter().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton btnConvert;
private javax.swing.JButton btnExit;
private javax.swing.JButton btnReset;
private javax.swing.JComboBox<String> comboBoxFrom;
private javax.swing.JComboBox<String> comboBoxTo;
private javax.swing.JLabel lblAnswer;
private javax.swing.JLabel lblConvertFrom;
private javax.swing.JLabel lblConvertTo;
private javax.swing.JPanel pnlAnswer;
static javax.swing.JTextField txtField1;
// End of variables declaration                   




}

1 个答案:

答案 0 :(得分:3)

您的代码似乎在for循环中多次调用JOptionPane,您将要移动:

if(comboBoxFrom.getSelectedItem().equals(comboBoxTo.getSelectedItem())){
之前 for循环。你不想多次打电话。并在它之后调用return;以退出监听器。实际上,在try块之前移动它:

private void btnConvertActionPerformed(java.awt.event.ActionEvent evt) {                                           
    String userInput = txtField1.getText(); //userInput equals to whatever the user typed in txtField1

    // check this out *** here ***
    if(comboBoxFrom.getSelectedItem().equals(comboBoxTo.getSelectedItem())){
        JOptionPane.showMessageDialog(null, "Cannot convert to the same unit type.", 
                "Um, You Forgot Something!!", JOptionPane.INFORMATION_MESSAGE);
        return;
    }

    try{
        Double.parseDouble(userInput); //checks to see if the userInput from the txtField1 is an integer if not the catch takes control

        for(String s: UNIT_NAME){
            if((comboBoxFrom.getSelectedItem().equals(s)) && comboBoxTo.getSelectedItem().equals("Centimeters")){