[英]How to make JTextField appear after a button click and only accept the same length of characters as another string -Java GUI
我之前曾發布過類似的問題,但被意外刪除。
我的JTextField應該在單擊按鈕后出現,但只有在最小化窗口之后才會出現。 另一個問題是,當它只應接受一定長度的短語時,它將接受單個字符。
因為它太長了,所以這里有一些代碼:
static String answer = "MY PUZZLE", puzzle = "M- -U----";
//inside constructor
guess = new JTextField("Write in Caps");
guess.setVisible(false);
guess.addActionListener(this);
board.add(guess);
//actionperformed
guess.setVisible(true);
gueStr = guess.getText();
if (gueStr.length() != answer.length()) //if it is not the same length
{
gueStr = "";
}
如果按下字母按鈕(此處未顯示代碼)作為“答案”字符串中的字符,或者用戶的猜測與答案字符串相同,則更改字符串“拼圖”
if ( gueStr.equals(answer)) //if the guess is the answer
{
puzzle = answer;
}
for(int x=0; x < answer.length(); x++) //go through answer
{
if(letter == answer.charAt(x)) //if the letter pressed matches a character in answer
{
puzzle = puzzle.substring(0,x) + letter + puzzle.substring(x+1); //substitute in letter
}
}
如果需要更多代碼來理解,我可以發布它。 我很樂意提供一些指導:D
編輯:
感謝所有幫助人員,但是我還沒有成功理解第二部分。
現在,我可以顯示文本字段,但是問題在於接受一定的字符長度。 它的長度必須與另一個字符串的長度完全相同,不能多於或少於。
我曾嘗試用你們提供的鏈接來實現它,但最后卻感到困惑(抱歉)。 有人可以提供一個具體的例子嗎?
編輯:
使用validate()並添加guess.setActionCommand(“ 1”)之后解決 。
使用InputVerifier
驗證您的文本輸入
請參考以下示例:
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JTextField;
class PassVerifier extends InputVerifier {
public boolean verify(JComponent input) {
JTextField tf = (JTextField) input;
String text = tf.getText();
// do your validation
// if (text.equals(answer)) //if the guess is the answer
// {
// puzzle = answer;
// }
// for (int x = 0; x < answer.length(); x++) //go through answer
// {
// if (letter == answer.charAt(x)) //if the letter pressed matches a character in answer
// {
// puzzle = puzzle.substring(0, x) + letter + puzzle.substring(x + 1); //substitute in letter
// }
// }
return true; // return true or false according to validation
}
}
將InputVerifier
設置為JTextField
JTextField tf1 = new JTextField ("Type \"pass\" here");
tf1.setInputVerifier(new PassVerifier());
frame.validate()
validate方法用於使容器再次布置其子組件。 顯示容器后,修改此容器的子組件(添加到容器或從容器中刪除,或更改與布局有關的信息)時,應調用該方法。
這應該起作用而不是最小化窗口。
同樣在第二部分中,API提供了有關如何自定義文本字段的示例: https ://docs.oracle.com/javase/8/docs/api/javax/swing/JTextField.html
執行類似於它們僅接受大寫字符的方式,而是使用string.length()檢查長度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.