Question

I have an array of objects laid out through a GridLayout in a JPanel. I need to be able to recreate the object in an index in the array and have the GridLayout update to reflect this. As of yet, I cannot find anyway to "refresh" or redraw the GridLayout. Is it possible to refresh a GridLayout without creating the entire GridLayout or JPanel? Assume I do not have access to JFrame.

import javax.swing.*;
import java.awt.*;

public class Test
{
    public static void main(String args[])
    {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();

        panel.setLayout(new GridLayout(5,5));

        JLabel[][] labels = new JLabel[5][5];
        for (int i = 0; i < 5; i++)
        {
            for (int j = 0; j < 5; j++)
            {
                labels[j][i] = new JLabel("("+j+", "+i+")");
                panel.add(labels[j][i]);
            }
        }

        labels[0][0] = new JLabel("Hello World");

        //Without doing it this way (cause my objects can't do this)
        //labels[0][0].setText("Hello World!");

        frame.add(panel);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.pack();
        frame.setResizable(false);
        frame.setVisible(true);
    }
}
Was it helpful?

Solution

I don't understand why you can't just update the text on the label.

Why do you need to "recreate the object"? It makes no sense. But if you really need to do this then the code would be something like:

panel.remove(0);
panel.add(theNewLabel, 0);
panel.revalidate();
panel.repaint();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top