0

I have a simple static method that, when given a list of numbers has to create a JFrame holding a histogram.

I use a SwingWorker (the doInBackground() does the number crunching, the done() creates the frame and the ChartPanel).

Now I'd like to return a reference (or a Future) of the JFrame created in done() to whoever calls this static method. Is there a way to do so? I am saying returning a Future because obviously the JFrame only exists after the done() method is done.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
CarrKnight
  • 2,768
  • 2
  • 23
  • 25
  • You can use get() to retrieve the return value of your doInBackground() mehtod. I can´t tell you if it will work with a Future, never tried anything similar. – Jannis Alexakis Jul 26 '13 at 08:52
  • 2
    SwingWorker isn't to designated for creating a Swing Objects (event is possible, bunch of code examples here that contains), create this Object off_screen, place there JComponents, layout JComponents (doesn't matter on apps start), call pack() and setVisible() in done() wrappped into invokeLater – mKorbel Jul 26 '13 at 08:55
  • 1
    expl. - > SwingWorker is only the bridge betweens Workers Threads and Swing Objects, from methods publish(), proccess(), setProcess() and done() guarantee that output will be notified EDT – mKorbel Jul 26 '13 at 09:00
  • @mrKorbel I am not sure I understood the comment. Of course JFrame/JComponents constructors can only be called in EDT(AT ALL TIMES: http://www.velocityreviews.com/forums/t707173-why-does-jdk-1-6-recommend-creating-swing-components-on-the-edt.html ). Even if I don't use SwingWorker and rather use invokeLater I still can't return the JFrame reference since it will only be filled in on a different thread. I am asking how to build a Future to reference a newly created Jframe when it's going to be created on EDT (SwingWorker or the invokeLater, doesn't matter) – CarrKnight Jul 26 '13 at 09:14
  • @jannis-alexakis thanks, but get() returns the results of doInBackground() not so much the "results" of done() – CarrKnight Jul 26 '13 at 09:15
  • See also [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/a/9554657/418556) – Andrew Thompson Jul 26 '13 at 10:05
  • The question wouldn't change if you were to substitute JFrame with JPanel, but thank you for the link. Very interesting! – CarrKnight Jul 26 '13 at 12:13

1 Answers1

2

As an alternative to waiting for done(), create your frame and chart panel on the EDT, publish() interim results and update your chart's dataset in process(). As shown in this example, the chart listens to changes in the dataset and should update automatically.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045