循环jtextfields,以便在输入除整数之外的任何内容时清除

时间:2016-11-05 19:27:49

标签: java loops jtextfield

我知道我需要这个代码循环,但我不知道该怎么做,就像我不知道该怎么做循环?它会在一分钟内清除所有文本字段,但我只想删除除了整数之外的任何文本字段。任何帮助将不胜感激。

try {
    int a = Integer.parseInt(theApp.tred.getText());
    int b = Integer.parseInt(theApp.tgreen.getText()); // uses
                                                        // information
                                                        // entered
    int c = Integer.parseInt(theApp.tblue.getText());

    if (a < 0) {
        a = 200; // if statements for values above and below the targets
                            // set
        tred.setText("200");
    }

    if (a > 255) {
        a = 255;
        tred.setText("255");
    }
    if (b < 0) {
        b = 200;
        tgreen.setText("200");
    }

    if (b > 255) {
        b = 255;
        tgreen.setText("255");
    }

    if (c < 0) {
        c = 200;
        tblue.setText("200");
    }
    if (c > 255) {
        c = 255;
        tblue.setText("255");
    }
    message.setText(" work submitted by:"); // text
    message.setForeground(new Color(a, b, c)); // changes colour to
                                                        // desired input

} catch (NumberFormatException ex) {

    message.setText("invalid input! please enter numbers only"); // text
    message.setForeground(new Color(0, 0, 0)); // original text set to
                                                // red
    tred.setText("");
    tgreen.setText("");
    tblue.setText(""); // clears box if not an integer
}

1 个答案:

答案 0 :(得分:1)

您可以将protocol NumberCalculation { var number : NSNumber { get set } } protocol Rule { // define associated type that conforming types must satisfy // by providing a type to replace it with associatedtype Value var invalidMessage : String { get set } func performRule(value: Value) -> Bool } struct GreaterThanRule : Rule, NumberCalculation { var invalidMessage: String var number : NSNumber init(valueMustBeGreaterThan value: NSNumber, withInvalidMessage message : String = "") { number = value invalidMessage = message } // satisfy associated type implicitly by annotating the type of the parameter // as NSNumber – the compiler will infer that Value == NSNumber. func performRule(value: NSNumber) -> Bool { number.decimalValue // works value.decimalValue // also works! return true } } 块分为3个部分:

try-catch

(这仅适用于int a = -1; try { a = Integer.parseInt(theApp.tred.getText()); if (a < 0) { a = 200; tred.setText("200"); } if (a > 255) { a = 255; tred.setText("255"); } //do the needed things here } catch (Exception e) { message.setText("invalid input! please enter numbers only"); // text message.setForeground(new Color(0, 0, 0)); tred.setText(""); } ,其他几乎相同)。