TAGS :Viewed: 12 - Published at: a few seconds ago

[ JButton to print a letter ]

How do you print a letter of the button a user clicked and then disable that button

I use a for loop to generate the buttons of each letter

   } for (int i = 65; i <= 90; i++) {
        btnLetters = new JButton(" " + (char) i);
        letterJPanel.add(btnLetters);
        letterJPanel.setLayout(new FlowLayout());
        btnLetters.addActionListener(this);

    }

When the button is clicked it should print the letter and then disable the button

public void actionPerformed(ActionEvent ae) {

    if (ae.getSource() == btnLetters) {

    }
}

Answer 1


if (ae.getSource() == btnLetters) { } }

this part will work only for the very last button created, so I consider it senseless.

Better do something like that

if (ae.getSource() instance of JButton &&
    ((JButton ) ae.getSource()).getText().length()==2) {
    PRINT(((JButton ) ae.getSource()).getText().substring(1));
    ((JButton ) ae.getSource()).setEnabled(false);
}

where PRINT is the actual printing (however you do that)

Answer 2


Create a new class

public class ButtonDisabler implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        JButton button = (JButton)e.getSource();
        System.out.println(button.getText() + " pressed");
        button.setEnabled(false);
    }
}

Then add it to each button

btnLetters.addActionListener(new ButtonDisabler());

Answer 3


First of all, i would do it like: (much better to look at, than casting from integer)

for(char c = 'A'; c <= 'Z'; c++)
{
    button.setText(""+c);
    ...
}

then

public void actionPerformed(ActionEvent ae) 
{
    //assuming you only set the action for the JButtons with letters
    JButton button = (JButton) ae.getSource();
    String letter = button.getText();
    print(letter); //for example System.out.println();
    button.setEnabled(false);
}

Answer 4


Maybe using an inner class will be easier

When creating the button.

JButton button = new JButton("A");
button.addActionListener(new ActionListener(
    public void actionPerformed(ActionEvent e){
      printMethod(button.getLabel()); //You have to implement this...
      this.disable()
});