gpt4 book ai didi

java - 如何从 JButton 获取按下的字母并将其与字符串进行比较

转载 作者:行者123 更新时间:2023-11-30 09:33:17 25 4
gpt4 key购买 nike

按下时从 JButton 获取字母

  public class ButtonDisabler implements ActionListener {

@Override
public void actionPerformed(ActionEvent e) {
JButton btnGetText = (JButton) e.getSource();
char charLetterPressed;
charLetterPressed=(btnGetText.getText().charAt(1));

btnGetText.setEnabled(false);
}
}

然后使用该字母并将其与字符串进行比较,然后仅当在 JLabel 中找到该字母时才显示该字母

 char charChkWord;
StringBuffer word = new StringBuffer();
for (int i = 0; i < strRandomWord.length(); i++) {
charChkWord = strRandomWord.charAt(i);
if (charLetterPressed == String.valueOf(charChkWord)) {
lblWord.setText(word.append(charChkWord).toString());
}
}

我不确定如何获取该字母并将其与字符串进行比较。

最佳答案

我支持 trashgod,如果可以的话,我会避免 KeyListeners

我还将按钮的文本设置为您要使用的字符和/或设置按钮的名称

JButton btnA = new JButton("A");
btnA.setName("A");

这将允许您选择如何在按钮上显示文本,同时为您提供一种方法来提供可能对您更有用的附加信息...

JButton button = (JButton) evt.getSource();
String text = button.getText();
// If you wanted to use the name of the button instead...
String name = button.getName();

// You would use this if you need part of the text...
char charPressed = Character.toLowerCase(text.charAt(0));
// You could to this to convert the character to a String for easier
// comparison...
String strCharPressed = Character.toString(text.charAt(0)).toLowerCase();

// A sample
String word = "This is a test";

// Finds the first occurrence of the character in the String...
// Comparison is case sensitive...
// If indexOf > -1 then the word contains the character
int indexOf = word.toLowerCase().indexOf(charPressed);
// Or, you just check to see if it is contained in the word...
boolean contains = word.toLowerCase().contains(Character.toString(charPressed));

System.out.println("indexOf = " + indexOf);
System.out.println("contains = " + contains);

关于java - 如何从 JButton 获取按下的字母并将其与字符串进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12268770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com