Search code examples
javaswingmodal-dialogjtextareajdialog

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

Solution

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