javastringswingfor-loopjbutton

How to get pressed letter from JButton and compare it to a string?


I want to get a pressed letter from JButton when it was pressed

  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);
    }
}

Then, use that letter and compare it to a string, then display the letter, only if it was found, into a 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());
        }
    }

I'm not sure how to get that letter and compare it to the string.


Solution

  • I'm with trashgod, I'd avoid KeyListeners if you can.

    I'd also set the text of the button to the character you want to use and/or set the name of the button as well

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

    This would allow you to make a choice over how you want to display the text on the button while providing you a means for providing additional information that might be more useful to you...

    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);