首页 > 解决方案 > Swing/awt gcd 计算器

问题描述

我必须在 java swing/awt 中创建一个计算不同函数的计算器。

例如它需要计算 GCD。
首先我创建了 UI,然后是 actionPerformed 函数,但是当我gcd在 GUI 中执行该函数时,屏幕会冻结。

calculate2.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Get values from text fields
            try {
                int a = Integer.parseInt(input1.getText());
                int b = Integer.parseInt(input2.getText());
                while (a != b) {
                    if(a > b)
                        a = a - b;
                    else
                        a = b - a;
                }

                String result1 = "" + (b);
                result.setText((result1));
            } catch (Exception f) {
                JOptionPane.showMessageDialog(rootPane, "ERROR: " + (f.getMessage()));
            }

            String aField = input1.getText();
            String bField = input2.getText();

            if (e.getSource() == calculate2) {

                if ("".equals(aField) || "".equals(bField)) {
                    String emptyFieldWarning;
                    emptyFieldWarning = "One or more fields is/are empty!";
                    JOptionPane.showMessageDialog(rootPane, emptyFieldWarning);
                }
            }
        }
    });

标签: javaswingawt

解决方案


在 while 循环中,在 else 分支中,语句应该是b = b - a


推荐阅读