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

标签 java string swing for-loop jbutton

按下时从 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/

相关文章:

java - 为什么Tomcat启动后就关机了?

python - 根据 .CSV 文件中字典键的出现次数进行计数

java - XML文本处理

java - 将固定数量的 for 循环转换为参数化数量时出现问题

java - 从元素列表中的 json 加载

excel - 如何从 Excel 中的文本字符串中记忆出正确的数字?

c - 分割字符串并转换为 Int

java - 删除 Jtable 中的行后出错

java - 修改 addMouseListener()

java - 单击按钮后 Swing 自动重新绘制 JPanel