0

New to Swing, but not to Java. I am trying the following:

public void actionPerformed(ActionEvent e) {

methodA();
pane.repaint();
methodB();
pane.repaint();

}

Where methodB() takes a long time. I would like it to paint twice, yet the first paint call never happens. It's as if I did:

public void actionPerformed(ActionEvent e) {

methodA();
methodB();
pane.repaint();

}

Sorry if this is basic, but I've tried searching and I still don't understand why.

I've tried calling paint directly, which works as intended, except the application flickers on every repaint.

satno
  • 1
  • 2
    Different scenario, different calls, but same behaviour and same solution: [Java swing GUI freezes](https://stackoverflow.com/questions/11185485/java-swing-gui-freezes) – BackSlash Jun 19 '17 at 08:28
  • `repaint()` is a request to paint the component _soon_ (not immediately). But if `methodB` takes a long time, it will hold up the event dispatch thread and nothing will get repainted until it is finished. Consider running `methodB` in another thread. – khelwood Jun 19 '17 at 08:28

1 Answers1

4

actionPerformed is called in the Event Dispatch Thread (EDT) which is also where the painting is executed, repaint only flags the component to be repainted. That means that the painting only can be done after actinPerformed finishes executing.

Long running tasks should not be executed in the EDT, use a SwingWorker or another Thread.

Indicated to study Swing's Threading Policy!

user85421
  • 28,957
  • 10
  • 64
  • 87