user1052335
user1052335

Reputation:

Change JPanel contents in JDialog

I'm trying to add components to a JDialog after it has been created and displayed. Nothing I try makes the changes actually update to the screen, and I've read and applied every question I could find related to this.

This example code creates a modal JDialog showing the word "test". I cannot get it to display "test2". Almost exactly the same code but with a JFrame instead of a JDialog behaves as I expect, so I don't understand. I'm new to Java and especially to swing.

import javax.swing.*;
public class DialogTester {
    public static void main(String[] args) {
        new DialogTester();
    }

    public DialogTester() {
        JFrame jframe = new JFrame();
        jframe.setVisible(true);
        JDialog jdialog = new JDialog(jframe,true);
        JPanel jpanel = new JPanel();
        jpanel.add(new JLabel("test"));
        jdialog.add(jpanel);
        jdialog.setVisible(true);
        jpanel.add(new JLabel("test2"));
        jpanel.revalidate();
        jdialog.getContentPane().validate();
        jdialog.pack();

    }
}

I also tried calling

jdialog.repaint();

which did nothing.

Upvotes: 1

Views: 1427

Answers (1)

JB Nizet
JB Nizet

Reputation: 691645

You created a modal dialog. So, as soon as you call setVisible(true), the following instructions wait for the dialog to be closed to be executed.

Put the code adding a label before the dialog is made visible, or put it in an event handler called after the dialog is shown, for example, when you click on a button in this dialog.

Upvotes: 4

Related Questions