willyRG
willyRG

Reputation: 83

How can I refresh the JPanel?

I want to do a dynamic form in Swing. When I call firstly the dataShow method, it creates the GUI. But when I call it again, it keeps the old panel and display the new at the background.

And when I try to remove the current panel, and then add the new. The GUI became empty

A Thread listen to events (int id in that case).

here is my code to display the dynamic form :

 public void showData(int id) throws DAOException, ClassNotFoundException{

        FormDAOImpl form = new FormDAOImpl();
        String b = form.importTagPoint(id);
        //if(compteur%2 == 0) {System.out.println("Compteur : " +compteur); scrollPane.remove(panel); 
        //frame.getContentPane().remove(scrollPane);
        //}
        panel = new JPanel(new MigLayout());

        if(b == null) b = "";
        String[] bits = b.split("\\,");
        String delims = "[=]";
        while(i<bits.length){
            textField = new JTextField();
            String[] bitsS = bits[i].split(delims);
            textField.setText(bitsS[1]);

            JLabel label = new JLabel(bitsS[0]+ " :    ");
            panel.add(label);
            panel.add(textField, "span, grow, alignx center, flowx");
            i++;
        }

        JButton annuler = new JButton("Annuler");
        JButton enregistrer = new JButton("Enregistrer");

        panel.add(annuler);
        panel.add(enregistrer);
        panel.revalidate();
        panel.repaint();

        scrollPane = new JScrollPane(panel);
        scrollPane.revalidate();
        scrollPane.repaint();

        frame.getContentPane().add(scrollPane);
        //frame.repaint();
        frame.invalidate();
        frame.validate();
        frame.repaint();

        frame.pack();
        frame.setMaximumSize(new Dimension(300, 800));

        compteur++;
    }

Upvotes: 0

Views: 1569

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347314

First, try calling frame.getContentPane().removeAll() to remove anything that was previously added to it. Obviously do this before you add anything new to it.

Second, try and devise a solution where you don't need to do this, but maintain a single view which can be updated via setters and getters if possible.

If you are literally changing views (show the user something complete different), consider using a CardLayout or JTabbedPane instead

Upvotes: 2

Related Questions