Search code examples
javasqlswingjtextfieldconcurrency

JTextField not correctly updating


I'm currently developing an utility which is executing queries on a MySQL database and I'm currently working on the interface.

When the user clicks on the button "Connect", the status bar (JTextField) text should change to "Connecting...". This works correctly:

connectButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            statusBar.setText("Connecting...");
            }
        }
    });

I implemented a function to connect to a database then the "Connect" button is clicked:

connectButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Class.forName("com.mysql.jdbc.Driver");
            statusBar.setText("Connecting...");
            connection = DriverManager.getConnection("jdbc:mysql://" + database);
            }
        }
    });

In this case, the text of the status bar doesn't change to "Connecting..." until the connection is established.

I removed some of the code, like exception handling, for improved readability.

How can I force the text of the status bar to change before the connection is established?


Solution

  • Establishing a database connection should not be performed in the Event Dispatch Thread. This is preventing your component from updating. Instead, perform the task in a background thread.

    If you need to report results while this action is taking place, either use the SwingWorker class, or update the component using the SwingUtilities class, in particular, invokeLater. Both of these will assure that the component(s) are updated on the EDT and that the long-running task takes place elsewhere.

    For more information, please read Concurrency in Swing.