sb33 sb33 - 27 days ago 7
Java Question

looping jtextfields so it clears if anything but an integer is entered

I know i need this code looped but I'm not sure how to do it, like i don't know what to have as the loop? it clears all the textfields at the minute, but i only want the textfield that has anything but an integer cleared. any help would be appreciated.

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


}

Answer

You can separate the try-catch block into 3 parts:

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

(this is just for tred, the others are pretty much the same).

Comments