【问题标题】:Make change program GUI更改程序 GUI
【发布时间】:2013-12-10 02:34:48
【问题描述】:

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

我的 gui 是什么样子的

原始代码

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 编辑器的带有 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 中的文本框中获取用户输入,但我完全不知道如何实现这一点

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

还找到了一个有用的 tut,但无法使用它来尝试完成我想要的工作。

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

【问题讨论】:

  • 使用 getText()。在你的 actionPerformed() 中使用它
  • 如果你不明白,我建议你在开始使用 gui 编辑器之前阅读关于 swing 的 oracle 教程,但基本上 gui 是事件库.. 当你点击按钮 jButton1ActionPerformed(evt); 这个方法得到执行,在这里你得到输入的数据!
  • 我可以用 getText() 代替扫描仪吗?

标签: java swing user-interface actionlistener jtextfield


【解决方案1】:

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

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

在您的情况下,您的控制台应用通过以下方式与用户交互:

  1. 输出输入提示
  2. 接受输入

现在,您必须解决如何将这两种交互更改为 GUI 布局。它应该对现有代码进行极少的修改,同时添加 GUI 代码来处理输入/输出。

在您的情况下,您有一个用作提示的标签、一个容纳输入的文本区域和一个用作接受输入的按钮。

所以你的程序流程是这样的:用户输入到 textarea -> 用户点击提交 -> 系统接受输入并处理它 -> 系统输出变化为 Quarters、Dimes 等。

现在,我们编写代码...

第 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,您只需设置代表季度、一角钱等金额的 JComponent 的文本。目前您的总数似乎缺少标签/文本区域,所以我会先添加它们,然后使用 setText(A)、setText(B) 等。

【讨论】:

  • 太棒了,我想我已经掌握了大部分内容,你知道我如何从另一个按钮中提取变量吗? gyazo.com/fc62c0e8be51c00b29fd1fe0dfa8ce39
  • 你的意思是在另一个方法中声明的变量,例如在另一个ActionPerformed中的jButton1ActionPerformed中的季度?在您的情况下,唯一的方法是将整数声明为全局变量,因此它们都可以在与您的方法相同的封装级别中访问。例如,jButton1 和 jButton1ActionPerformed 处于同一级别。所以如果你搬了宿舍;到定义了 jButton1 的同一区域,您可以在类中的任何方法中访问它。
  • Nvm 我想通了。谢谢你,穆
【解决方案2】:

这不是一个 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       


    }

【讨论】:

    猜你喜欢
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多