【问题标题】:How to validate the Input of the User in a Swing?如何在 Swing 中验证用户的输入?
【发布时间】:2017-07-01 07:54:43
【问题描述】:

我创建了一个控制台应用程序,现在启动它以转换为摇摆应用程序。我有一个问题,我多次搜索你的答案,但我没有找到任何答案。

我的应用程序有一个类来验证用户的输入,如果输入错误,它会在控制台中显示错误消息。所以我尝试做的是,我有一个 Jtextfield 并验证这个输入,如果输入错误它应该给我错误消息。

这是我的 Input 类,允许用户编写

public class Input {

    private static BufferedReader eingabe = new BufferedReader(new InputStreamReader(System.in));
    private Output output = new Output();

    private static String captureText() throws Exception {
        return eingabe.readLine();
    }
    public String formatInput() {
        boolean again = true;

        while (again) {
            try {
                String format = captureText();

                if (!format.equalsIgnoreCase("Y") && !format.equalsIgnoreCase("N")) {
                    again = true;
                    throw new Exception();
                }
                again = false;
                return format;
            } catch (Exception e) {
                this.output.formatInputWrong();
            }
        }
        return null;

    }
}

这就是我的输出类方法

void formatInputWrong() {
    System.out.print("\nThe Format Input is wrong.");

}

我只是想知道我可以使用 Input 类的 Validation 还是应该为摇摆输入验证创建一个特殊的类,因为我知道我可以取出 JTextfield 的 Input

【问题讨论】:

  • 这实际上取决于您要验证的字段类型 - 您可以使用 InputVerifier,它是后期验证过程,或者对于文本组件使用 DocumentListenerDocumentFilter跨度>
  • 您还可以通过附加到JButtonActionListener 进行后验证
  • 是的,我会用按钮完成它,但正常的控制台验证不起作用,对吗?因此,我发布的代码是我的控制台验证如何工作的示例。
  • 大多数 GUI 都是事件驱动的框架,也就是说,有些事情发生了,你就会做出响应。可能需要一点时间来适应。基本上,您不需要任何类型的循环(由您负责),您只需在触发相应事件时对其进行响应

标签: java swing validation input


【解决方案1】:

您的错误消息现在出现在控制台上。看起来您希望消息出现在 GUI 中。如How to Use the Focus Subsystem: Validating Input所示,InputVerifier是一个不错的选择。因为shouldYieldFocus() 的实现允许有副作用,所以您可以根据需要更新状态显示。从这个完整的example开始,下面的变体添加了一个JLabel,并根据调用verify()的结果将其设置在shouldYieldFocus()中。

private static final String OK = "Values OK.";
private JLabel status = new JLabel(OK, JLabel.CENTER);
…
if (verify(input)) {
    …
    status.setText(OK);
    return true;
} else {
    …
    status.setText("Please enter a number.");
    return false;
}

补充方法可能包括DocumentListener,如建议的here

import java.awt.*;
import javax.swing.*;

/**
 * @see http://stackoverflow.com/a/44861290/230513
 * @see http://stackoverflow.com/a/11818183/522444
 */
public class VerifierEg {

    private static final String ZERO = "0.0";
    private static final String OK = "Values OK.";
    private JTextField field1 = new JTextField(ZERO, 5);
    private JTextField field2 = new JTextField(ZERO, 5);
    private JTextField resultField = new JTextField(ZERO, 10);
    private JLabel status = new JLabel(OK, JLabel.CENTER);

    private void createAndShowGui() {
        resultField.setEditable(false);
        resultField.setFocusable(false);

        JPanel mainPanel = new JPanel();
        final JTextField[] fields = {field1, field2};

        mainPanel.add(field1);
        mainPanel.add(new JLabel(" x "));
        mainPanel.add(field2);
        mainPanel.add(new JLabel(" = "));
        mainPanel.add(resultField);

        for (JTextField field : fields) {
            field.setInputVerifier(new MyInputVerifier(field));
        }

        JFrame frame = new JFrame("VerifierEg");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(mainPanel);
        frame.add(status, BorderLayout.SOUTH);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private void calcProduct() {
        double d1 = Double.parseDouble(field1.getText());
        double d2 = Double.parseDouble(field2.getText());
        double prod = d1 * d2;
        resultField.setText(String.valueOf(prod));
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                VerifierEg eg = new VerifierEg();
                eg.createAndShowGui();
            }
        });
    }

    /**
    * @see http://stackoverflow.com/a/11818946/230513
    */
    private class MyInputVerifier extends InputVerifier {

        private JTextField field;
        private double value;

        public MyInputVerifier(JTextField field) {
            this.field = field;
        }

        @Override
        public boolean shouldYieldFocus(JComponent input) {
            if (verify(input)) {
                field.setText(String.valueOf(value));
                calcProduct();
                status.setText(OK);
                return true;
            } else {
                field.setText(ZERO);
                field.selectAll();
                status.setText("Please enter a number.");
                return false;
            }

        }

        @Override
        public boolean verify(JComponent input) {
            try {
                value = Double.parseDouble(field.getText());
                return true;
            } catch (NumberFormatException e) {
                return false;
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 2011-06-26
    • 1970-01-01
    相关资源
    最近更新 更多