V
V
VasG2011-10-16 11:35:38
Java
VasG, 2011-10-16 11:35:38

How to dynamically load images in JPanel in Java?

There is batch processing of images, and I would like the processed image to be displayed immediately on the JPanel.
Right now I'm using code like this:

for  ( int  i  =  0 ;  i  <  photosToDetect. length ;  i ++ )  {
        …
        jPanel1 . setLayout ( new  FlowLayout ( ) ) ;
        jPanel1. setVisible ( false ) ;
        jPanel1. add ( new  JLabel ( new  ImageIcon ( scaledSource150x100 ) ) ) ;
        jPanel1. setVisible( true ) ;
        …
}

Unfortunately, pictures are displayed only after the end of the program (loop), and all at the same time.
Actually, the question is: how to avoid this? How to make sure that the images are displayed exactly during the execution, and not all at once and only at the end of the cycle?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
asm0dey, 2011-10-16
@VasG

You need to throw image processing into a separate thread (SwingWorker), and basically only update the UI.

L
leventov, 2011-10-16
@leventov

Try like this

for (int i = 0; i < photosToDetect.length; i++) {
        …
        jPanel1.add(new JLabel(new ImageIcon(scaledSource150x100)), 0);
        jPanel1.repaint();
        …
}

S
spiff, 2011-10-16
@spiff

You need to do it in a separate thread. Either in a SwingWorker or use SwingUtils.invokeLater()/SwingUtils.invokeAndWait();
Working with UI components not through EDT (Event Dispatch Thread) is not correct.

I
in_finiti, 2011-10-16
@in_finiti

Ilya Semenov
Guys who have an account on Habré, write to the lucky one that he does not have repaint after loading into the panel, and that the panel itself is visible (visible = true) only at the stage of creating a new layout, otherwise my heart is breaking from suggested answers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question