I’m relatively new to Java and decided to mess around a bit with Swing. I wanted to build an application that updates a counter either up or down depending on a button click.
Everything was going great until I got to the point where I had to add a listener to one of the buttons. I added a button and modified a piece of code I found online:
addHome.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
addHomeCount++;
}
});
I want the addHomeCount to be increased when the button is clicked. If I add
System.out.println(addHomeCount);
within the method, it outputs the code to the console window perfectly. However, when I add that same code outside of the method, it just returns 0.
Is there a way I can get that incrementing addHomeCount integer outside of the actionPerformed method and place it in a JLabel? I have read about the getActionCommand(), but I’m not sure if that is what I am looking for here.
The reason it is printing 0 is because the code outside of the listener executes right away. The listener code only executes when you press the button so it isn’t happening until after the print statement.
I think all you need to do is set the JLabel text from inside the action listener.