【问题标题】:Handling several events in one JButton在一个 JButton 中处理多个事件
【发布时间】:2020-03-10 03:38:00
【问题描述】:

我有一个摄氏到华氏转换器的作业,它会问这样的事情:

  1. 用户应插入摄氏值,点击“转换”按钮,得到华氏值;

  2. 用户应插入华氏值,点击“转换”按钮,得到摄氏值;

  3. 显示温度转换结果后,如果再次单击“转换”按钮,则应清除 GUI 中的所有输入-输出文本字段。

但是,我很难在一个按钮中实现多个操作。我的错误在哪里(jButton1ActionPerformed 中的事件代码)?

Java中有一段代码,我用的是Netbeans 8.1:如下

import java.util.Scanner;
import javax.swing.JOptionPane;

public class TConverter extends javax.swing.JFrame {

/**
 * Creates new form TConverter
 */
public TConverter() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jTextField1 = new javax.swing.JTextField();
    jTextField2 = new javax.swing.JTextField();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setText("Celcius");

    jLabel2.setText("Fahrenheit");

    jButton1.setText("Convert");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jButton2.setText("Reset");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    jTextField1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jTextField1ActionPerformed(evt);
        }
    });

    jTextField2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jTextField2ActionPerformed(evt);
        }
    });

    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(52, 52, 52)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jButton1)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(19, 19, 19)
                            .addComponent(jLabel1)))
                    .addGap(39, 39, 39))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel2)
                    .addGap(47, 47, 47)))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jTextField1)
                .addComponent(jTextField2))
            .addContainerGap(177, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(72, 72, 72)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(27, 27, 27)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel2)
                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(48, 48, 48)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton1)
                .addComponent(jButton2))
            .addContainerGap(90, Short.MAX_VALUE))
    );

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

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    jTextField1.setText("");
    jTextField2.setText("");
}                                        

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


}                                           

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

}                                           

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

    float CelciusInput = Float.parseFloat(jTextField1.getText());
    float FahrenheitInput = Float.parseFloat(jTextField1.getText());


    if (!(jTextField1.getText().isEmpty()))
    {
        try
        {

        jTextField2.setText(String.valueOf((CelciusInput * 1.8) + 32));

        }
        catch (Exception ex)
        {

        }
    }

    else if (!(jTextField2.getText().isEmpty()))
    {
        try
        {
        jTextField1.setText(String.valueOf((FahrenheitInput - 32) * 5 / 9));
        }
        catch (Exception ex)
        {

        }
    }

    else if (String.valueOf(jTextField2.getText()).equals(String.valueOf(jTextField1.getText())))
    {
            jTextField1.setText("");
            jTextField2.setText("");
    }

    else
    {
             JOptionPane.showMessageDialog(null, "Wrong type of input",
                "Error dialog message", JOptionPane.ERROR_MESSAGE);
    }






}                                        

/**
 * @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(TConverter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(TConverter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(TConverter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(TConverter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

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



// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration    }

【问题讨论】:

  • 我认为您应该设置标志并使用if..else if...else 来考虑所有结果。例如,isUserInputCelsius == true 会告诉你打电话给convertCelToFarenheit()isUserInputCelsius == false 会告诉你做相反的事情,isResultShownOnDisplay == ? 会同时陪你确认true,然后打电话给clearDisplay()。给你准确的代码不会帮助你学习,但祝你一切顺利!而且你显然在进步!
  • 在没有先检查String 是否为空之前,您不应调用Float.parseFloat

标签: java swing try-catch jbutton actionlistener


【解决方案1】:

试试下面的代码,看看它是否适合你:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    float CelciusInput;
    float FahrenheitInput;
    if (!(jTextField1.getText().isEmpty())) {
        if (jTextField2.getText().isEmpty()) {
            try {
                CelciusInput = Float.parseFloat(jTextField1.getText());
                jTextField2.setText(String.valueOf((CelciusInput * 1.8) + 32));               
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "Wrong type of input",
                        "Error dialog message", JOptionPane.ERROR_MESSAGE);
                jTextField1.setText("");
                jTextField2.setText("");
                return;                   
            }                           
        } else {
            jTextField1.setText("");
            jTextField2.setText("");                
        }
    } else if (!(jTextField2.getText().isEmpty())) {
        try {
            FahrenheitInput = Float.parseFloat(jTextField2.getText());
            jTextField1.setText(String.valueOf((FahrenheitInput - 32) * 5 / 9));
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Wrong type of input",
                    "Error dialog message", JOptionPane.ERROR_MESSAGE);
             jTextField1.setText("");
             jTextField2.setText("");             
        }
    }
}

【讨论】:

  • 感谢您的回答!有效!有一段时间,如果我在转换后写入一些值,Button 也会删除字段。如果转换是否处理,是否可以添加一些额外的检查?如何添加?
  • @Ulvi 我不太明白你的意思。使用我提供的代码,只要只有一个 TextField 有值,就会发生转换。如果两个字段都有值(例如在转换后),按钮将清除它们。
  • 好的。但是为什么 jTextField1.setText("");和 jTextField2.setText("");已添加到捕获部分?
  • 这是一个假设,当输入一些无效输入时,应该清除/重置字段。随意删除它
  • 另外,如果我的代码对您有所帮助,如果您可以投票或接受它作为答案,那就太好了
【解决方案2】:

您已经了解了如何处理事件。要根据输入执行不同的操作,您必须检查这些条件(就像您已经做的那样)......

将它们放入单独的方法中会很有帮助

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    if (isCelsionSet() && !isFarenheitSet() )
    {
        convertCelsiusToFarenheit();
    }
    else if(!isCelsionSet() && !isFarenheitSet()){
        notifyEmptyFields();
    }
    else if(!isCelsionSet() && isFarenheitSet()){
        convertFarenheitToCelsius();
    }
    else if(isCelsionSet() && isFarenheitSet()){
        clearInput();
    }
}                                        

现在您可以单独测试和验证每个方法

private boolean isCelsionSet(){
    //FIXME rename jTextField1 into celsiusInput
    try{
        Float.parseFloat(jTextField1.getText());
        return true; //field is indeed properly set
    }catch(NumberFormatException e){
        return false; //field is not properly set
    }
}

private void convertFahrenheitToCelsius(){
    //FIXME rename jTextField2 into farenheitInput
    float celsius = getTempInCelsius();
    jTextField2.setText(String.valueOf((celsius * 1.8) + 32));
}

如果您遵循这条道路,您将很容易发现错误并创建可读和可维护的代码。

很抱歉,我没有阅读您的所有代码,它(希望很快不会再)乱七八糟,现在......

测试注意事项

更改代码后,您可以轻松创建测试:

@Test
public void testIsCelsiusEmpty(){
   TConverter tconverter = new TConverter();
   tconverter.celsiusInput.setText("12.3"); //after renaming jTextField1 into celsiusInput
   Assert.assertTrue(tconverter.isCelsionSet());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 2015-05-11
    相关资源
    最近更新 更多