Susheel K
Susheel K

Reputation: 25

Update an entire JFrame, including all JComponents

I'm trying to update a JFrame, and all of the components in the frame, including JPanel, JLabel components, etc. I tried using revalidate(), but that didn't seem to be working. I have a JLabel in the frame displaying an int, and I have the int iterating by 1 when I click a JButton. I can see that the value of the int changes, but the actual text on the label doesn't change. I know I can use JLabel.setText(), but is there a method to use for all components, that would update the displayed text/image upon pressing a button?

Here is my code below:

package repainttest;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class Window extends JFrame {
    int test = 1;
    JLabel label;

public Window() {
    setLayout(new FlowLayout());

    label = new JLabel(Integer.toString(test));
    add(label);

    JButton button = new JButton("Add");
    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
          test +=1;
            System.out.println(test);
            refresh();
        }
    });
    add(button);

    setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public void refresh() {
    SwingUtilities.updateComponentTreeUI(this);
    revalidate();
    repaint();
    }
}

Upvotes: 0

Views: 181

Answers (1)

Sanjeev Saha
Sanjeev Saha

Reputation: 2652

If you do not set the new text (test) on the JLabel, it is never going to know that the value of test is changing. So, please insert following statement:

label.setText(String.valueOf(test));

in public void actionPerformed(ActionEvent e) after following statement:

test +=1;

and see the results.

Upvotes: 3

Related Questions