Java GUI actionPerformed() 问题

标签 java user-interface jlabel

所以我一直在为我的大学类(class)制作这个 GUI 温度转换器,我几乎完成了,但我不明白为什么我无法使用按钮 btnCalc 来显示不同复选框的结果。如果我这样做它会显示一些内容

if(ae.getSource()==btnCalc) JOptionPane.showMessageDialog(this,"Button");

无论如何,如果解决这个问题,我将非常感谢任何帮助。我只想让程序在点击计算按钮后显示结果。

package TempConverter;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;

/**
 *
 * @author 00220682
 */
public class TempConvertGUI extends javax.swing.JFrame implements ActionListener{


public TempConvertGUI() {
    initComponents();
    btnCalc.addActionListener(this);
    degrees.addActionListener(this);
    CtoF.addActionListener(this);
    FtoC.addActionListener(this);
}

/**
 * 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() {

    buttonGroup1 = new javax.swing.ButtonGroup();
    jLabel1 = new javax.swing.JLabel();
    degrees = new javax.swing.JTextField();
    btnCalc = new javax.swing.JButton();
    lblResults = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    CtoF = new javax.swing.JCheckBox();
    FtoC = new javax.swing.JCheckBox();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Temperate Converter");

    jLabel1.setText("Enter The Degrees:");

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

    btnCalc.setText("Calculate");
    btnCalc.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            btnCalcMouseClicked(evt);
        }
    });
    btnCalc.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnCalcActionPerformed(evt);
        }
    });

    jLabel2.setText("What would you like to convert?");

    buttonGroup1.add(CtoF);
    CtoF.setText("Celcius to Fahrenheit");
    CtoF.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            CtoFActionPerformed(evt);
        }
    });

    buttonGroup1.add(FtoC);
    FtoC.setText("Fahrenheit to Celcius");
    FtoC.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            FtoCActionPerformed(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()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(degrees, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(btnCalc, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(FtoC)
                                    .addGap(32, 32, 32)
                                    .addComponent(CtoF))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(60, 60, 60)))))
                    .addGap(0, 0, Short.MAX_VALUE))
                .addComponent(lblResults, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1)
                .addComponent(degrees, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(FtoC)
                .addComponent(CtoF))
            .addGap(18, 18, 18)
            .addComponent(btnCalc, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(lblResults, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

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

private void degreesActionPerformed(java.awt.event.ActionEvent evt) {                                        
     CtoF.setEnabled(true);
     FtoC.setEnabled(true);
}                                       

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

}                                    

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

}                                    

private void btnCalcMouseClicked(java.awt.event.MouseEvent evt) {                                     

}                                    

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

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new TempConvertGUI().setVisible(true);
            CtoF.setEnabled(false);
            FtoC.setEnabled(false);

        }
    });
}

// Variables declaration - do not modify                     
public static javax.swing.JCheckBox CtoF;
public static javax.swing.JCheckBox FtoC;
static javax.swing.JButton btnCalc;
private javax.swing.ButtonGroup buttonGroup1;
public static javax.swing.JTextField degrees;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel lblResults;
// End of variables declaration                   

@Override
public void actionPerformed(ActionEvent ae) {

     double display = 0;
     double x = 0;
     CtoF DegreesC = new CtoF(0);
     FtoC DegreesF = new FtoC(0);



     if(ae.getSource()==CtoF){
            double DinC = Double.parseDouble(degrees.getText());
            DegreesC.setDegrees(DinC);
            display = DegreesC.CtoFconvert();
            x = 1;
     }
     else if (ae.getSource()==FtoC){
            double DinF = Double.parseDouble(degrees.getText());
            DegreesF.setDegrees(DinF);
            display = DegreesF.FtoCconvert();
            x = 2;
     }

     if (ae.getSource() == btnCalc){

            if (x == 1){
                lblResults.setText("<html>Degrees in Celcius: " + degrees.getText() + "<br>Degrees in Fahrenheit: " + display);
            }
            else if (x == 2){
                lblResults.setText("<html>Degrees in Fahrenheit: " + degrees.getText() + "<br>Degrees in Celcius: " + display);
            }         



  }


}

}

最佳答案

我不确定我是否完全理解这个问题,但看看这是否有帮助......

您在复选框和计算按钮上使用相同的 ActionListener。您的构造函数使用以下内容初始化它们

btnCalc.addActionListener(this);
degrees.addActionListener(this);
CtoF.addActionListener(this);
FtoC.addActionListener(this);

因此,当按下其中任何一个时,该 Action 监听器就会触发。添加多个更小、更具体的操作监听器可能比添加一个需要检查源代码的大监听器更有意义。因此,btnCalc 的操作监听器将显示结果,并且其他每个按钮都将有自己的操作监听器来设置它们需要设置的变量。

关于Java GUI actionPerformed() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26350362/

相关文章:

java - 从数据库表中选择列并在java中重命名它们

.net - 使用 WPF 创建类似于 Windows 资源管理器的 GUI

java - 领域模型和用户界面

java - setVisible(false) 为一组 JTextField 和 JLabel

java - 无法跨程序访问jlabel

java - 有没有办法用 JNI 设置 DirectByteBuffer 内存?

java - 如何在java中显示iText Image对象

linux - 电脑时钟重启,CentOs无法启动GUI

java - 使用 if 语句和单选按钮在 Jlabel 上显示文本

java - 即时从 .tgz 文件夹中读取文件