0

I am trying to update the jtextarea after displaying JDialog but it is not updating can anyone help me.

public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setBounds(0, 0, 500, 500);
        frame.setVisible(true);
        JDialog dialog = new JDialog(frame);
        dialog.setModal(true);
        JPanel panel = new JPanel();
        dialog.add(panel);
        final JTextArea area = new JTextArea();
        panel.add(area);
        dialog.setBounds(100, 100, 200, 200);
        area.setLineWrap(true);
        area.setText("bbbbbbbbbbbb");
        dialog.setVisible(true);
        area.setText("zzzz");
    }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Bharat Sharma
  • 3,926
  • 2
  • 17
  • 29

2 Answers2

4

It's modal. Set modal to false or add the area.setText() call somewhere in the dialog. E.g. by adding a listenter on dialog visible.

StanislavL
  • 56,971
  • 9
  • 68
  • 98
4

The call to dialog.setVisible is blocking. This means that the statement area.setText("zzzz") will not be executed until AFTER the dialog is closed.

This is simply the nature of modal dialogs

UPDATE

In order to be able to update the UI like this, you need to be a little sneaky...

public class TestDialog {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setBounds(0, 0, 500, 500);
                frame.setVisible(true);

                JDialog dialog = new JDialog(frame);
                dialog.setModal(true);
                JPanel panel = new JPanel();
                dialog.add(panel);
                final JTextArea area = new JTextArea();
                panel.add(area);
                dialog.setBounds(100, 100, 200, 200);
                area.setLineWrap(true);
                area.setText("bbbbbbbbbbbb");

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        SwingUtilities.invokeLater(new Runnable() {

                            @Override
                            public void run() {
                                System.out.println("Hello");
                                area.setText("zzzz");
                            }
                        });
                    }
                }).start();

                dialog.setVisible(true);
            }
        });
    }
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366