简体   繁体   English

我需要帮助。 我正在编写一个具有GUI的程序

[英]I need help. I'm writing a program that has a GUI

The user will enter a number between 1 and 99. I've got most my code written I just can't figure out out to get it to calculate with the calculate button. 用户将输入一个介于1到99之间的数字。我已经编写了大多数代码,只是想不出要使用“计算”​​按钮进行计算。 I could really use some step by step help I'm willing to learn if some one can help me. 我真的可以使用一些逐步的帮助,我愿意了解是否有人可以帮助我。 I'm a very beginner. 我是一个初学者。

package minimumchris;

import javax.swing.JButton;
import javax.swing.JTextField;


public class useri extends javax.swing.JFrame {


    public useri() {
        initComponents();
    }


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

        jScrollPane1 = new javax.swing.JScrollPane();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("enter a number between 1-99");

        jLabel2.setText("quarters");

        jLabel3.setText("dimes");

        jLabel4.setText("nickels");

        jLabel5.setText("pennies");

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

        jButton2.setText("clear");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 197, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 47, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .add(66, 66, 66)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel5)
                            .add(jLabel4)
                            .add(jLabel3)
                            .add(jLabel2))
                        .add(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 195, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButton2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 177, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(16, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel1))
                .add(32, 32, 32)
                .add(jLabel2)
                .add(18, 18, 18)
                .add(jLabel3)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jLabel4)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel5)
                .add(29, 29, 29)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(jButton2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE)
                    .add(jButton1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(32, Short.MAX_VALUE))
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        int cntrquart = 0;
        int cntrdimes = 0;
        int cntrpennies = 0;
        int cntrnickels = 0;



         JTextField jTextField=new JTextField(); // initialize textFild
         JButton calculate =jButton1;




       int quarters = Integer.parseInt(jTextField.getText());


        while (quarters >= 25)

        {
           quarters = quarters  - 25;
           cntrquart++;


        }


//dimes 
        int dimes = quarters;


        while (dimes >= 10)

        {
           dimes = dimes  - 10;
           cntrdimes++;
        }



//nickels 
        int nickels = dimes;


        while (nickels >= 5)
        {
           nickels = nickels  - 5;
           cntrnickels++;
        }



//pennies
        int pennies = nickels;


        while (pennies >= 1)
        {
           pennies = pennies  - 1;
           cntrpennies++;
        }
        jLabel2.setText("Quarter" + cntrquart );
        jLabel3.setText("Dimes:" + cntrdimes );
        jLabel4.setText("Nickels:" + cntrnickels );
        jLabel5.setText("Pennies:" + cntrpennies );
    }                                        

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

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new useri().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.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   
}

Problem is you're using a brand new JTextField when "calculate" is pressed: 问题是按下“计算”时您正在使用全新的JTextField:

JTextField jTextField=new JTextField(); // useless
JButton calculate =jButton1; // useless

int quarters = Integer.parseInt(jTextField.getText()); // should use jTextField1 (probably)

Like RC said with the line: 就像RC所说的那样:

JTextField jTextField=new JTextField();

You are creating a new JTextField object which is not want you want. 您正在创建一个不需要的新JTextField对象。 Since the variables you have are class instances you can refer to them directly as such: 由于您拥有的变量是类实例,因此可以这样直接引用它们:

int quaters = Integer.parseInt(jTextField1.getText());

Creating a new variable means entire new distinct set of parameters for that variable and instance-specific data (like whats inside the box of a JTextField ) is not shared. 创建新变量意味着共享该变量的完整的新参数集,并且共享实例特定的数据(例如JTextField框内的内容)。 Since you are (presumably) populating the JTextField jTextField1 with text, the text can only be retrieved via calling getText() upon the jTextField1 object itself. 由于(大概)用文本填充了JTextField jTextField1 ,因此只能通过在jTextField1对象本身上调用getText()来检索文本。

Besides the point but might I suggest using more intuitive variable names and only copying the relevant parts of the code. 除了重点,我可能建议使用更直观的变量名,并且仅复制代码的相关部分。 This helps us find your issue more quickly. 这有助于我们更快地找到您的问题。 Please also make your question title specific to the problem itself, "I need help" isn't going to get you anywhere. 还请针对问题本身设置问题标题,“我需要帮助”不会助您一臂之力。

As a final point, your code can be further optimized and simplified if you replace your loops with simple division/mod operations. 最后一点,如果您使用简单的除法/ mod操作替换循环,则可以进一步优化和简化代码。 Instead of: 代替:

while (quarters >= 25){
    quarters = quarters  - 25;
    cntrquart++;
}

int dimes = quarters;

//...

do: 做:

cntrlquart = quarters / 25; //Integer division
int dimes = quarters % 25; //Mod operation, remainder of dividing by 25.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM