Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

building BufferedImage not in EDT - good or bad?  RSS feed

 
Piotr Gajowy
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a piece of code that builds a BufferedImage from scratch - let's say 10k dots. It takes some time, a few hundreds ms. From time to time I am trying to rebuild the image. If I do it on EDT, it freezes whole GUI for the time given. My question is: Is it possible to prepare somehow this BufferedImage outside the EDT so the process will not freeze the screen? Or maybe it would be a bad practise? How should I cope with the situations, when my image is build in such a long time?

Thanks

Piotr
 
Rob Spoor
Sheriff
Posts: 21090
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Building the image in a different thread is OK, as long as you don't access the user interface for it - not for displaying, not for querying.
 
Darryl Burke
Bartender
Posts: 5167
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a read of the Swing concurrency tutorial and SwingWorker.
 
Piotr Gajowy
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am a bit familiar with SwingWorker, but I am not sure it is ok to use in this case. Is it ok to do something like this:

- in doInBackground(){
BufferedImage bImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D gi = (Graphics2D) bImage.getGraphics();
//draw ellipses and lines on gi
gi.dispose();

-in done()
drawImage(bImage, 0, 0, this); - on components Graphics

Second quick question - can I access Component's method .getHeight from other than EDT threads?


 
Rob Spoor
Sheriff
Posts: 21090
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Piotr Gajowy wrote:-in done()
drawImage(bImage, 0, 0, this); - on components Graphics

You shouldn't do that. The component should get a reference to the BufferedImage, which it should draw in its paintComponent method. The done method should then set the BufferedImage and call repaint(). Assuming this SwingWorker is declared inside the component itself, this should then be part of your SwingWorker

Second quick question - can I access Component's method .getHeight from other than EDT threads?

You really shouldn't. This method is not thread safe. If the component is resized while you query this method the results are unpredictable.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!