制作更改程序GUI

时间:2013-12-10 02:34:49

标签: java swing user-interface actionlistener jtextfield

几周前我为了做出改变而编写了一个程序,现在我试图把这个程序变成一个gui并且有点问题。我可以使用Netbeans Jframe编辑器制作gui并使gui看起来漂亮,这使得我的问题很简单,我的问题是试图找出如何插入我的代码。我将我的程序插入第一个Jbutton,但无法弄清楚如何从gui而不是程序获取用户输入。我点击Jbutton,它要求控制台完成工作而不是gui。请帮忙。

我的gui是什么样的

enter image description here

原始代码

public static void main (String[] Args) {

    // Initialize varriables
    int quarters = 25;
    int dimes = 10;
    int nickles = 5;
    int pennies = 1;

    //Loop starts here
    while(true) {

    System.out.println("Enter in a number between 1-99");

    // Blank Output for spacing
    System.out.println();
    // User Input "remember this for reference"
    Scanner Userinput = new Scanner(System.in);


   int input = Userinput.nextInt();


   //while loop end
   if(input<1) {
    break;  //break is a keyword that exits the loop when a condition is met.
   }

   int q = input/quarters;
   input -= q*quarters;
   String A = "Quarters:" +q;

    //Blank Output for spacing
    System.out.println();


   //output quarters
   System.out.println(A);


   int d = input/dimes;
   input -= d*dimes;
   String B = "Dimes:" +d;

   //output dimes
   System.out.println(B);


   int n = input/nickles;
   input -= n*nickles;
   String C = "Nickles:" +n;

   //output nickles
   System.out.println(C);


   int p = input/pennies;
   input -= p*pennies;
   String D = "Pennies:" +p;

   //output pennies
   System.out.println(D);




  } 





   }

使用Netbeans Jframe Editor的GUI的当前代码

import java.util.Scanner;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Christ
 */
public class coin extends javax.swing.JFrame {


public coin() {
    initComponents();
}


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

    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 (1-99)");

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

    jLabel2.setText("Quarters");

    jLabel3.setText("Dimes");

    jLabel4.setText("Nickles");

    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");

    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()
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE,        179, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(68, 68, 68)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addComponent(jLabel3)
                .addComponent(jLabel4)
                .addComponent(jLabel5))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(22, 22, 22)
            .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(55, 55, 55)
            .addComponent(jLabel2)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jLabel3)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jLabel4)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jLabel5)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 53, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap())
    );

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

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

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


    // Initialize varriables
    int quarters = 25;
    int dimes = 10;
    int nickles = 5;
    int pennies = 1;

    //Loop starts here
    while(true) {

    System.out.println("Enter in a number between 1-99");

    // Blank Output for spacing
    System.out.println();
    // User Input "remember this for reference"
    Scanner Userinput = new Scanner(System.in);


   int input = Userinput.nextInt();


   //while loop end
   if(input<1) {
    break;  //break is a keyword that exits the loop when a condition is met.
   }

   int q = input/quarters;
   input -= q*quarters;
   String A = "Quarters:" +q;

    //Blank Output for spacing
    System.out.println();


   //output quarters
   System.out.println(A);


   int d = input/dimes;
   input -= d*dimes;
   String B = "Dimes:" +d;

   //output dimes
   System.out.println(B);


   int n = input/nickles;
   input -= n*nickles;
   String C = "Nickles:" +n;

   //output nickles
   System.out.println(C);


   int p = input/pennies;
   input -= p*pennies;
   String D = "Pennies:" +p;

   //output pennies
   System.out.println(D);




  } 







}                                        

/**
 * @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(coin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(coin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(coin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(coin.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 coin().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.JTextField jTextField1;
// End of variables declaration                   
}

现在我认为需要的是抛弃插入用户输入到控制台的扫描仪来完成工作,并以某种方式从gui的文本框中获取用户输入,但我完全不知道如何实现这一点< / p>

也是一个初学者,所以如果你能让它易于理解将非常感激,简单是最好的。

还发现了一个帮助但却无法使用它来尝试按我想要的方式工作的啧啧。

链接到Tut http://www.codeproject.com/Articles/33536/An-Introduction-to-Java-GUI-Programming

2 个答案:

答案 0 :(得分:2)

Netbeans多年前因创建复杂的GUI代码而赢得了声誉。从来没有真正为自己测试过,但这似乎是一个非常简单的应用程序的代码。

将基于控制台的应用程序转换为基于GUI的应用程序时,您必须问自己这个问题: 用户如何与系统交互?

在您的情况下,您的控制台应用与用户进行了以下互动:

  1. 输出输入提示
  2. 接受输入
  3. 现在,您必须解决如何将这两种交互更改为GUI布局的问题。它应该包含对现有代码的极少修改,同时添加GUI代码来处理输入/输出。

    在您的情况下,您有一个用作提示的标签,一个包含输入的文本区域,以及一个用作接受输入的按钮。

    所以程序的流程是这样的:用户输入textarea - &gt;用户点击提交 - &gt;系统接受输入并处理它 - &gt;系统输出按季度,尺寸等变化

    现在,我们编码...

    第1步:设置GUI机制。你有那个下来

    步骤2:处理用户输入:您在处理程序中为“计算”按钮执行此操作,在您的情况下,该按钮似乎是jButton1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // Initialize varriables
        int quarters = 25;
        int dimes = 10;
        int nickles = 5;
        int pennies = 1;
    
        try {
            int input = Integer.parseInt(jTextField1.getText());
        }
        catch (NumberFormatException e) {
            //prompt user to enter an integer, not erroneous input
            //e.printStackTrace();
        }
    
        //future code
    }
    

    请注意输入与控制台应用程序中的功能相同,我们只是通过不同的方式获取它。由于GUI系统是由用户输入驱动的,我们不应该连续循环直到用户输入有效输入,我们只是告诉用户他们的输入是无效的,然后让他们输入一个有效的数字。我们检查数字是否有效(在1到99之间输入)并进行处理,否则什么都不做(并提示输入有效数据?)

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // Initialize varriables
        int quarters = 25;
        int dimes = 10;
        int nickles = 5;
        int pennies = 1;
    
        try {
            int input = Integer.parseInt(jTextField1.getText());
        }
        catch (NumberFormatException e) {
            //prompt user to enter an integer, not erroneous input
            //e.printStackTrace();
        }
    
        //if input in the range of [1, 99]
        if(1 <= input && input <= 99) {
            //do processing
        }
        else {
            //prompt user for valid input, for example by using JOptionPane
        }
    }
    

    现在:输出。而不是在A,B,C和D上执行System.out.println,您只需要设置代表四分之一,一角硬币等金额的JComponents文本。目前你似乎缺少总计的标签/ textareas,所以我先添加那些,然后使用setText(A),setText(B)等等。

答案 1 :(得分:0)

这不是一个100%的解决方案我花了很长时间为你调整它以便你找到一个退出

试试这段代码

package test;


    import java.util.Scanner;
import java.util.Scanner;

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */

    /**
     *
     * @author Christ
     */
    public class coin extends javax.swing.JFrame {


    public coin() {
        initComponents();
    }


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

        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 (1-99)");

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

        jLabel2.setText("Quarters");

        jLabel3.setText("Dimes");

        jLabel4.setText("Nickles");

        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");

        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()
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE,        179, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(68, 68, 68)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .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(55, 55, 55)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 53, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

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

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

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


        // Initialize varriables
        int quarters = 25;
        int dimes = 10;
        int nickles = 5;
        int pennies = 1;

        //Loop starts here


        System.out.println("Enter in a number between 1-99");

        // Blank Output for spacing
        System.out.println();
        // User Input "remember this for reference"
        Scanner Userinput = new Scanner(System.in);


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



       int q = input/quarters;
       input -= q*quarters;
       jLabel2.setText("Quarter: "+q);

        //Blank Output for spacing
        System.out.println();


       //output quarters


       int d = input/dimes;
       input -= d*dimes;
       jLabel3.setText("Dimes: "+d);

       //output dimes


       int n = input/nickles;
       input -= n*nickles;
       jLabel4.setText("Nickles: "+n);

       //output nickles


       int p = input/pennies;
       input -= p*pennies;
       jLabel5.setText("Pennies: "+q);

       //output pennies





    }                                        

    /**
     * @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(coin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(coin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(coin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(coin.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 coin().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.JTextField jTextField1;
    // End of variables declaration       


    }