0

I run 2 tasks in this sequence:

  1. Run first task
  2. First task is done
  3. Wait for user to press a button
  4. Run second task
  5. Second task is done
  6. Exit

I made a small, simple GUI to show what is happening. This is what it should look like for each step.

  1. enter image description here

2, 3. enter image description here

  1. enter image description here

5, 6. enter image description here

In practice, the 4. GUI doesn't happen at all, it just stays as done while doing the second task and then goes straight to done without the button (5, 6.).

This is my code:

// Setting up the GUI
JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
contentPane.setLayout(new BorderLayout());

ImageIcon loading = new ImageIcon("loading.gif");
JLabel label = new JLabel("loading... ", loading, JLabel.CENTER);

contentPane.add(label, BorderLayout.CENTER);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);

// Do the first task
for (int i = 0; i < 50000; i++) {
    System.out.println(i);
}

// Show when the task is done
label.setIcon(null);
label.setText("done");

// Add the button that must be clicked to continue
JButton startButton = new JButton("check");
startButton.addActionListener(e -> {
    contentPane.remove(startButton);
    label.setIcon(loading);
    label.setText("loading...");
    frame.validate();

    // Do the second task
    for (int i = 0; i < 50000; i++) {
        System.out.println(i);
    }

    // Show when it's done
    label.setIcon(null);
    label.setText("done");
    frame.validate();
});
contentPane.add(startButton, BorderLayout.SOUTH);
frame.validate();

How to I make it so that the GUI updates to loading before running task2?

I've tried to do an inner class, to change GUI components to fields and call another method, nothing seems to work. Any help appreciated.

Touniouk
  • 375
  • 1
  • 13
  • 1
    Either use a Swing Timer if you're doing some count-down or a background thread if running long code so as not to freeze the Swing event thread. Please read [Concurrency in Swing](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html) for more on this. – Hovercraft Full Of Eels Nov 14 '17 at 13:18
  • for (int i = 0; i < 50000; i++) { System.out.println(i); } Only takes about 232 miliseconds on my PC. Why don't you use a Thread.sleep(5000); to test if it works? – Rens Groenveld Nov 14 '17 at 13:22
  • Thanks @HovercraftFullOfEels, I will. – Touniouk Nov 14 '17 at 13:40
  • @RensGroenveld I did initially but then figured the sleep was somehow blocking the frame from updating. The time was noticeable enough here. – Touniouk Nov 14 '17 at 13:43
  • Sorry, I was also mistaken, Hovercraft is right. – Rens Groenveld Nov 14 '17 at 13:50

0 Answers0