im trying to solve that problem for days. My program editing images. im not using multithreading.
i am using a function (private void console()) that writes formatted text in a JTextPane. i have a class called ImageWork() that works with my pictures.
my problem: i call first the console("start with work")
function, after that i call a
function of my class to editing an image (it takes some time). then i called another time my console("finish") function. i have tried many things that the method to editing the image wait till the console function is ready without success :(.
so every time i call the 3 functions first the image will be edited, then the console function writes in my textpane both texts.
private void color2gray()
{
console("start")
try
{
myImg.color2gray();
console("success");
repaint();
}
catch (Exception e)
{
console("no success");
}
the program works fine. my problem is that i want that text in my console (JtextPane) that the function starts now and then the function color2gray starts because that function could take one minute with big pictures.
i have already tried things like change console return type to boolean and call that:
while (!(console("start")) {};
I would be pleased if there finds someone an solution for that problem. Thanks
console() code:
private void console(String str,boolean fehler)
{
time=new GregorianCalendar();
String help=time.getTime().toString();
help=help.substring(0,19);
doc = (StyledDocument) console.getDocument();
Style style = doc.addStyle("StyleName", null);
StyleConstants.setForeground(style, Color.black);
try { doc.insertString(doc.getLength(),help, style); }
catch (BadLocationException e) { e.printStackTrace(); }
if (fehler) StyleConstants.setForeground(style, Color.red);
else StyleConstants.setForeground(style, new Color(0,125,0));
try { doc.insertString(doc.getLength()," : "+str+"\n", style); }
catch (BadLocationException e1) { e1.printStackTrace(); }
}
What is the name of the thread that invokes color2gray()? Add this to the first line of that function to find out:
System.out.println("Thread = " + Thread.currentThread().getName());
You may see an output like this:
Thread = AWT-EventQueue-0
Which means the code is running on the "event thread". This should be the only thread that modifies Swing/GUI components. AND this thread should NOT do long-running work. If this is the event thread, then you need to do your long work in the background.
change
myImg.color2gray();
to
Thread t = new Thread() {
@Override
public void run() {
myImg.color2gray();
}
};
t.start();
As a start. And read more about the swing event thread:
http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html http://en.wikipedia.org/wiki/Event_dispatching_thread