0

I am new to Swing to bear with me. I am using a JTextField to display status messages as a process runs. The process starts when a JButton is clicked. Inside the action, I would like to change the JTextField value multiple times while the process runs so the user knows what's happening. The problem is, the JTextField value doesn't update until the method that the button calls is complete. Therefore, only the last message is actually displayed.

Here is some code:

My button:

JButton runButton = new JButton("Run Test");
runButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent b) {
            changeProgressText("Progress: Running test script...");
            runTest();
}});

My runTest() method:

public void runTest() {
    int numRows = table.getRowCount();
    javax.swing.table.TableModel model = table.getModel();

    // Loop through the table values and execute the web service
    try {
        for (int i=0; i < numRows; i++) {
            if (model.getValueAt(i, 2) != null) {
                if (model.getValueAt(i, 3) != null) {
                    changeProgressText("Progress: Executing " + model.getValueAt(i, 2) + model.getValueAt(i, 3));
                    Thread.sleep(500);
                } else {
                    changeProgressText("Progress: Executing " + model.getValueAt(i, 2));
                    Thread.sleep(500);
                }
            }
        }
    } catch (Exception e) 
    {
        System.out.println(e.getMessage());
    }
    changeProgressText("Progress: Complete");
}

public void changeProgressText(String textValue) {
    progressText.setText(textValue);
    progressText.repaint();
    progressText.revalidate();  
}

Note: I am using a "sleep(500)" so there is a delay between messages so I can see if they're showing up or not. The only message that displays is "Progress: Complete".

Dan
  • 33
  • 6
  • 4
    You are performing two task, your time consuming task and one updating UI in same thread, separate them and it will help you solve your issue. Also try reading about `SwingWorker` – Shrikant Havale May 19 '15 at 20:56
  • Thanks! I was thinking along the same lines and even tried launching the message logic in another thread. It didn't work, but maybe I did something wrong. I will definitely give SwingWorker a try. That sounds like exactly what I need. – Dan May 20 '15 at 00:31

0 Answers0