Bharat Sharma
Bharat Sharma

Reputation: 3966

JTextArea not updating after display jdialog

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");
    }

Upvotes: 0

Views: 978

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347184

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);
            }
        });
    }
}

Upvotes: 4

StanislavL
StanislavL

Reputation: 57381

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.

Upvotes: 4

Related Questions