Pregunta

Tengo una matriz de objetos establecidos a través de un GridLayout en un JPanel. Tengo que ser capaz de crear el objeto en un índice de la matriz y tienen la actualización GridLayout para reflejar esto. Hasta el momento, no puedo encontrar alguna forma de "actualización" o redibujar el GridLayout. ¿Es posible actualizar un GridLayout sin crear todo el GridLayout o JPanel? Suponemos que no tengo acceso a 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);
    }
}
¿Fue útil?

Solución

No entiendo por qué no puede simplemente actualizar el texto en la etiqueta.

¿Por qué es necesario "volver a crear el objeto"? No tiene sentido. Pero si usted realmente necesita para hacer esto, entonces el código sería algo como:

panel.remove(0);
panel.add(theNewLabel, 0);
panel.revalidate();
panel.repaint();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top