Is it possible to change the text of the JButton when clicked? I have a JButton, the text is a number, what I would like to happen is when the user clicks it, the text in the button will increment. Is that possible? Thanks
Asked
Active
Viewed 789 times
3 Answers
1
You can access the clicked button by getSource()
method of ActionEvent
. Thus you can manipulate the button as much as you want.
Try this:
@Override
public void actionPerformed(ActionEvent e) {
JButton clickedButton = (JButton) e.getSource();
clickedButton.setText("Anything you want");
}

ogzd
- 5,532
- 2
- 26
- 27
0
Another way to do it:
JButton button = new JButton("1");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int count = Integer.parseInt(button.getLabel());
button.setLabel((String)count);
}
});

Rubens Mariuzzo
- 28,358
- 27
- 121
- 148

Syam Kumar S
- 832
- 2
- 8
- 26
0
This is a solution I created.
public int number = 1;
public Test() {
final JButton test = new JButton(Integer.toString(number));
test.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
number += 1; //add the increment
test.setText(Integer.toString(number));
}
});
}
First, an integer is created. Then, a JButton is created with the value of the integer cast to a string, since the text of a JButton can only be a string. Next, using an inner class, an action listener is created for the button. When the button is pressed, the following code is executed which increments the value of the integer and sets the text of the button to the value of the integer cast to a string.

ama291
- 70
- 1
- 10