I have a problem with this code:
public class Gui_01 extends JFrame {
private JPanel display;
private ActionListener visualizza() {
ActionListener evento = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
display.removeAll();
Thread t = new Thread(new Runnable() {
public void run() {
JPanel visualizza = new JPanel();
visualizza.add(new JLabel("Test", SwingConstants.CENTER));
display.add(visualizza, BorderLayout.SOUTH);
updateProgress(visualizza);
}
}
);
t.start();
}
};
return evento;
}
private void updateProgress(final JPanel visualizza) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
display.add(visualizza, BorderLayout.SOUTH);
}
});
}}
I don't understand why the code don't work properly, the thread t and the thread in updateProgress work fine, but any modification to display won't affect the GUI even with invokeLater.
display.add(visualizza, BorderLayout.SOUTH)
This code don't modify the gui, i know it's normal (due to Swing), but why invokeLater don't work.
Sorry for my bad english, thanks in advance for replys.
First get rid of the
display.add(visualizza, BorderLayout.SOUTH);statement in your thread. as you should never update or modify the UI from outside the context of the EDT...In fact, I'd discourage your from creating UI elements outside of the EDT, as you can't guarantee when they might start interacting with the UI.
Second, call
revalidateandrepaintafter you've updated the UI...Swing is lazy when it comes to updating the UI, this is a good thing, as it allows you to make sweeping changes and only update the UI when you're ready to do so.
I'd also encourage you to use a
SwingWorkerinstead, as it has functionality which you can use to synchronise the updates with the EDT. See Worker Threads and SwingWorker for more details