Threading a swing app basic question

S

Sam

All

I am fairly new at Swing and trying the foll.
Load an image to a Panel inside a SplitPane... and then make the
program to add another image after the first one. This is more of a
testing to learn threads better but here is the code i am faltering
with.

public class MyCanvas extends JFrame {

JSplitPane jSplitPane1 = new JSplitPane();

Image img;
JPanel jPanel1 = new JPanel();
VerticalFlowLayout verticalFlowLayout1 = new VerticalFlowLayout();


public MyCanvas() {
try {
setTitle("Frame Canvas");
jbInit();
} catch (Exception ex) {
ex.printStackTrace();
}
}

private void jbInit() throws Exception
{
this.getContentPane().add(jSplitPane1,
java.awt.BorderLayout.CENTER);
jPanel1.setLayout(verticalFlowLayout1);

// Adding the first image to be displayed.....
img = Toolkit.getDefaultToolkit().getImage("first.jpg");
img = img.getScaledInstance(70, 80, 0);
jPanel1.add(new JLabel(new ImageIcon(img)));
//
// Start running a thread to load one more...

Runnable updateComponent1 = new Runnable() {
public void run()
{
try
{
Thread.sleep(5000);
img =
Toolkit.getDefaultToolkit().getImage("second.jpg");
img = img.getScaledInstance(70, 80, 0);
jPanel1.add(new JLabel(new ImageIcon(img)));
} catch(Exception ex)
{
ex.printStackTrace();
}

validate();
}
};


javax.swing.SwingUtilities.invokeLater(updateComponent1);


}


public static void main (String args[]) {
MyCanvas frame = new MyCanvas();
frame.setSize(600,600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

From what i understand the invokeLater should only halt (because of the
sleep in the runnable) on the second image from being displayed. But
for me the frame shows up w/o the first image and then both first and
the second show up together. I think i am missing something here.
Please assist.

Thanks
Sam
 
S

sanjay manohar

From what i remember, I think invokeLater runs the specified runnable
in the AWT event processing thread. therfore your Thread.sleep() would
hold up event processing! Not what you intended eh?
Try new Thread(runnable).start() instead of invokeLater?
 
H

hilz

sanjay manohar said:
in the AWT event processing thread. therfore your Thread.sleep() would
hold up event processing! Not what you intended eh?
Try new Thread(runnable).start() instead of invokeLater?

and probably call just this line (the one in the runnable class):
jPanel1.add(new JLabel(new ImageIcon(img)));
from yet another thread using invokeLater, to run only this line in the awt
event thread.

thanks
hilz
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top