KnowledgeGeek
KnowledgeGeek

Reputation: 197

How to update JLabel from action listener?

Explanation:


I have an int variable to keep track of how many times button is pushed.

I have a JLabel that shows this variable in the form of a string basically.

When I click Add, I want the variable to update and then the jlabel to show the updated variable.

I have a secondary button listener class that implements the actionlistener code. I can't post all my code because my professor is strict about her plagiarism checks.

EDIT:

I see when I add the JLabel.setText to the action listener, it will update. Not sure if this is the best method.

Code:


int counter = 0;

JLabel label = new JLabel("Count is: " + counter);

JButton increment = new JButton("Increment Here");

increment.addActionListener(new ButtonListener());

My button listener class contains this code:

counter++;

Let me know if more code is necessary, I am just trying to simplify my issue. I tried adding an UpdateUI(); method, but nothing happened.

Upvotes: 1

Views: 1413

Answers (1)

Adnan Ahmad Khan
Adnan Ahmad Khan

Reputation: 644

in your Button Action Listener

Write

label.setText("Count is: " + counter);

After the Increment to count variable

Upvotes: 2

Related Questions