如何从JButton中按下字母并将其与字符串进行比较

时间:2012-09-04 17:46:10

标签: 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());
        }
    }

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

4 个答案:

答案 0 :(得分:1)

我无法推荐KeyListener。相反,让每个按钮知道它的名称,如下所示here

for (int i = 0; i < 26; i++) {
    String letter = String.valueOf((char) (i + 'A'));
    buttons[i] = new JButton(letter);
    north.add(buttons[i]);
}

然后,您可以使用contains()类中的String方法。

lblWord.getText().contains(button.getText());

答案 1 :(得分:1)

我有垃圾桶,如果可以,我会避免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);

答案 2 :(得分:0)

您可以使char charLetterPressed;超出方法范围。

您只需使用String.valueOf(charChkWord)即可charLetterPressed == charChkWord

if范围内,在设置标签文字后,使用break;退出for循环。

答案 3 :(得分:0)

使用以下代码获取KeyPressed

class MyKeyListener extends KeyAdapter {
  public void keyPressed(KeyEvent evt) {

     Char chr = evt.getKeyChar();

    }
  }

现在,一旦按下将其转换为字符串,请执行以下操作....

String s = new String(chr);

if(s.equals(charChkWord)){

   // Do something...

}else{

   // Do something...

}