我有一個名爲x的文本框。JTextfield,如何驗證getText()方法中的內容
當文本字段包含「」時,我想要做一些事情。如果沒有,請做其他事情。
我試着做
String test = x.getText();
if(test.startsWith(" ")){buttonN.setForeground(Color.GRAY));}
else{buttonN.setForeground(Color.BLACK));}
,但它沒有工作。任何建議
我有一個名爲x的文本框。JTextfield,如何驗證getText()方法中的內容
當文本字段包含「」時,我想要做一些事情。如果沒有,請做其他事情。
我試着做
String test = x.getText();
if(test.startsWith(" ")){buttonN.setForeground(Color.GRAY));}
else{buttonN.setForeground(Color.BLACK));}
,但它沒有工作。任何建議
(Color.GRAY))和(Color.BLACK))以2個右括號結尾,而只打開一個。
String test = x.getText();
if (test.startsWith (" "))
{
buttonN.setForeground (Color.GRAY);
}
else buttonN.setForeground (Color.BLACK);
括號周圍的一些空格使閱讀更方便。
爲什麼不使用contains
:
if(x.getText().contains("\u0020"))
buttonN.setForeground(Color.GRAY);
else
buttonN.setForeground(Color.BLACK);
雖然上述將工作,它不會檢測到表格間距。話雖這麼說,我會建議使用正則表達式代替:
if(Pattern.compile("\\s").matcher(x.getText()).find())
buttonN.setForeground(Color.GRAY);
else
buttonN.setForeground(Color.BLACK);
爲什麼要使用該空間的unicode值?我希望你在搜索「a」時不要使用「\ u0060」(如果這就是unicode的值)。你不應該使用幻數。 – camickr 2011-04-22 03:05:16
@camickr:WOW,如果我將「幻數」賦值給一個變量,你會感覺好點嗎......'private static final String SPACE =「\ u0020」;'?或者更好的是,如果我剛剛使用'「」'?放棄挑剔... – mre 2011-04-22 10:09:54
這不是挑剔。問這個問題的人顯然是一個初學者。許多初學者只是在不瞭解所有代碼的重要性的情況下使用提出的建議詞。你的解決方案應該鼓勵好的編程技術許多人可能知道unicode 20代表的是什麼,但我猜想人們知道什麼是'代表'。您編寫的代碼應該是自我記錄。我的建議是使用「」,這讓葉子懷疑你正在尋找的是什麼。 – camickr 2011-04-22 14:40:42
如果你只是想確保,如果不管它是否包含空格,製表符,換行符等使用下面的文本字段爲空:
if(x.getText().trim().length() == 0){
buttonN.setForeground(Color.GRAY);
}else{
buttonN.setForeground(Color.BLACK);
}
的String.trim()
消除在String的任何空白。
爲getText()
命令的任何verifycation最簡單的方法是這樣的:
If (field.getText().isEmpty()) {
buttonN.setForeground(Color.GRAY);
}
else {
buttonN.setForeground(Color.BLACK);
}
那是空白(製表符,空格,換行等)或只是一個空間? – Matt 2011-04-22 01:19:16
只是一個空間。 – razshan 2011-04-22 01:20:47
試試這個。只想確認一下。 Character.isSpaceChar(test.getChar(0)) – Matt 2011-04-22 01:23:34