2016-11-05 17 views
1

이 코드는 루프가 필요하지만 루프를 어떻게 처리해야할지 모르겠습니다. 분마다 모든 텍스트 필드를 지 웁니다. 그러나 정수 만 지운 텍스트 필드 만 필요합니다. 어떤 도움을 주시면 감사하겠습니다.jtextfields를 루핑하여 정수 만 입력하면 지울 수 있습니다.

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 
} 
+0

실제로 달성하려는 것은 무엇입니까? – aleb2000

+0

@ aleb2000 더 많은 코드가 있지만 기본적으로 3 개의 값 (적색 녹색과 파란색)을 입력하고 메시지를 입력 된 값을 나타내는 색으로 변경합니다. 난 그냥 255 이상의 숫자 또는 임의의 정수가 아닌 임의의 항목을 다루는 몇 가지 추가 작업을하려고합니다. – sb33

+0

여기 루프가 필요하다고 생각하지 않습니다. 대신 청취자를 추가 할 수 있습니다. 이 대답처럼'changeUpdate()'메소드를 구현 한 텍스트 필드 문서 : http://stackoverflow.com/a/3953219/5955649 – aleb2000

답변

1

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

(이것은 다른 사람이 거의 동일하며, 단지 tred입니다).

+1

그냥 시도했는데 만약 int a b c가 자신의 try에 정의되어 있고 calle 밖에있을 수 없기 때문에 원하는 입력으로 메시지를 변경하는 message.setforeground를 할 수 있습니까? – sb33

+0

@ sb33 변경을 구현하셨습니까? – ItamarG3

+0

이제 필드가 지워집니다! 그것은 좋은 메시지 일 뿐이지 만 잘못된 메시지를 표시하기는하지만 대답이 좋은 경우 – sb33