Using a SwingWorker in an Executor class?

Here's some code that works and does what I want but I don't know if its a good idea....
I have a program that may run one of a couple dozen long operations. I want to bring up a progress dialog to show the user how these operations are coming along.
I was using a swing worker every time I ran a long task but its a pain to make changes in so many different places. So I set up the approach below.
import java.util.concurrent.Executor;
import javax.swing.JOptionPane;
import com.sun.java.help.impl.SwingWorker;
* This class takes a long task as a Runnable and
* runs it while showing a progress dialog
public class MyExecutor implements Executor
     public void execute(Runnable r)
          final MySmallProgressWindow dialog;
          dialog = new MySmallProgressWindow();
          final Runnable fr = r;
          dialog.show("Testing Executor ") ;
          final SwingWorker worker = new SwingWorker()
               public Object construct()
                    try
                        fr.run();
                   catch(Exception g)
                         System.err.println(g);
                         JOptionPane.showMessageDialog(null, "Error: " + g.toString(), "Error", JOptionPane.ERROR_MESSAGE);
                   finally
                        dialog.hide();
                        System.out.println("Clean up here in finally");
                   return null;
               public void finished()
                       dialog.hide();
         worker.start();
I call it this way
MyExecutor execute = new MyExecutor();                   
Runnable runnableCopy = new Runnable() {
public void run() {
     someLongTask();
execute.execute(runnableCopy);Comments?
Message was edited by:
legoqueen

import javax.swing.*;
public class MyApplet extends JApplet {
     public void init() {
          //init stuff here
     public void start() {
          //start stuff here
     public static void main(String[] args) {
          JFrame f = new JFrame();
          JApplet a = new MyApplet();
          f.getContentPane().add(a);
          f.setSize(600, 400);
          f.setVisible(true);
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          a.init();
          a.start();
}Excuse me, but is there a way to do this on Applet only instead of JApplet... I was told we need to use Applet only...

Similar Messages

  • Use OBJCLASS object of Emigall for  Class & characteristics creation in FL

    Hi Fritz,
    Good day,
    I want to use OBJCLASS object of Emigall for
    Class and characteristics cration of Functional Location, The object is
    desiged for Equipment only,
    I read the document of this object which says
    that it can be modify to use for functional location as well by changing
    some rule, I tried by changing the field "Name of database table for
    object" from the standard which is made for DEVICE/EQUIPMENT
    I need your help to modify the rule to use this object for class and
    characterstic creation for Functional Location, the migration object field is set to Device
    which I want to change to FUNCLOC  but that field is not modifiable.
    Can you help me Fritz
    Regards,
    Robert

    Robert,
    Yes you are right. The following changes have to be made:
    HEADER-OBJECT_TYPE need to be set to IFLOT (Fixed Value or Transfer field rule)
    DATA-FIELD need to be set to TPLNR  (Fixed Value or Transfer field rule)
    DATA-VALUE need to be set to either CONNOBJ or DEVLOC (Via KSM field rule)
    Kind regards,
    Fritz

  • How do  I use a variable from an Interface class?

    Right now I have three classes. First class is called Game and it extends my second class call Parent and also implements my third class call Source. Source is an interface class. I have a variable that I want to use in my Source class named Checker. Now, How do I go among using that variable from my Game class? What should the code look like?
    ex.
    public class Game extends Parent implements Source
    need help badly....

    ok, what I forgot to tell you guys is that my variable
    in my interface class is a boolean type(true or
    false). It is set to true now. But I want it to change
    to false when a user triggers a button in the Game
    class. How do I do this? You don't because you can't. If you have a varaible declared in an interface it must be static and final. It cannot, therefore, be changed. Better head back to the drawing board.

  • Is it possible to querry all of the Virtual Instruments in a VI using the ActiveX Server Virtual Instrument Class?

    Is it possible to querry all of the Virtual Instruments that exist in the Front panel of a VI using the ActiveX Server Virtual Instrument Class? I can't seem to find a method or property that returns all the Instruments I may want to control from another application.
    I wish not to have to reference to the VI to figure the ControlName by looking at the VI FrontPanel.
    But rather have a prop that exposes the strings of all the Instruments.
    Example:
    allinstr=ObjectVIInstrument.VIControlNames
    Object.SetControlValue(AllInstr(1),value)
    Thanks.
    -Abe

    Abe,
    There is a VI method called "Get All Control Values" that returns an array of {name,typedesc,flatstrvalue} but this method is not exposed to ActiveX interface, most probably because type descriptors and flattened strings are data format internal to LabVIEW.
    However you can make a subVI that inputs the target VI name and returns the name of all controls on the Panel invoking the internal method. Then you call this VI via ActiveX to retrieve the list of Front Panel controls of the target VI.
    LabVIEW, C'est LabVIEW

  • How to use javasetters and getters in different classes

    how to use setters and getters in different class so that the setvalue in one class is effect in second class for getting

    If i got your question right,
    make sure your classes are in the same package
    make sure your getters are public/protected
    make sure your code calls the setter before calling the getter
    Kind regards

  • How to use replace(CharacterSequence, CharacterSequence) in String class

    Need simple java program using the following
    how to use replace(CharacterSequence, CharacterSequence) in String class
    Kindly help

    From http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#replace(java.lang.CharSequence,%20java.lang.CharSequence)
    replace
    public String replace(CharSequence target,
    CharSequence replacement)Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".
    Parameters:
    target - The sequence of char values to be replaced
    replacement - The replacement sequence of char values
    Returns:
    The resulting string
    Throws:
    NullPointerException - if target or replacement is null.
    Since:
    1.5

  • ClassCastException: You must use ResultSet from this driver!class webl

    Hi,
    I have configured the Connection pool and DataSources for SQLServer using inet-OPTA
    drivers.
    I am using the CachedRowSet implementation from inet and it seems to bomb out
    with the following error stack trace:
    STACK TRACE:
    java.lang.ClassCastException: You must use ResultSet from this driver!class webl
    ogic.jdbc.rmi.SerialResultSet
    at com.inet.tds.CachedRowSet.a(Unknown Source)
    at com.inet.tds.CachedRowSet.populate(Unknown Source)
    Any ideas of what is causing this problem ?
    Is it that i cannot use the CachedRowSet implementation from inet.
    If that is the case we have lot of code that uses this and i will have to change
    a lot.
    Any help is appreciated
    Thanks
    Venu

    The code is in one of the utility classes that is in the classpath and this utility
    class is used by the Stateless session EJB that i deployed in the WebLogic AppServer.
    As i understand, Weblogic 8.1 is out and i will try running on it.
    Thanks
    Venu
    Joseph Weinstein <[email protected]_this> wrote:
    >
    >
    venu wrote:
    Hi,
    I am running WebLogic version 7.0.2
    Do you have any idea when the 8.1 will be available (i believe it isstill in
    beta)
    I'll find out. Do answer my other question: Where is this code running
    that gets the exception?
    Joe
    - Srini
    Joseph Weinstein <[email protected]_this> wrote:
    venu wrote:
    Hi,
    I have configured the Connection pool and DataSources for SQLServerusing inet-OPTA
    drivers.
    I am using the CachedRowSet implementation from inet and it seems
    to
    bomb out
    with the following error stack trace:
    STACK TRACE:
    java.lang.ClassCastException: You must use ResultSet from this driver!classwebl
    ogic.jdbc.rmi.SerialResultSet
    at com.inet.tds.CachedRowSet.a(Unknown Source)
    at com.inet.tds.CachedRowSet.populate(Unknown Source)
    Any ideas of what is causing this problem ?
    Is it that i cannot use the CachedRowSet implementation from inet.
    If that is the case we have lot of code that uses this and i will
    have
    to change
    a lot.
    Any help is appreciated
    Thanks
    VenuHi. What version of the server are you using. This problem will goaway
    for 8.1.
    We currently wrap all JDBC objects from pooled drivers, to maintaincontrol
    over
    the pooled connection. Where is this code running that gets the exception.
    It seems that Inet's rowset implementation needs to cast the resultset
    it gets
    to be inet's result set object, in order to make some non-standardmethod
    calls.
    Joe

  • Using threads (SwingWorker) to update JTree component

    Hi,
    Im having a problem trying to update a JTree component (adding child nodes to an existing node) using threads. Im using the SwingWorker3 class (http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html) for threading.
    When the user selects a node for expansion, the logic for fetching the children of the selected node is executed under the construct() method of SwingWorker.
    Once this data is obtained, the job of adding the children to the selected node is done in the finished() method which runs on the event-dispatch thread as per documentation of SwingWorker3.
    The problem Im facing is that even though the data for the children is obtained and the finished() method executes and adds the children to the selected node, they are not visible in the UI.
    If anybody knows how this can be resolved, please let me know. Any help/pointers would be greatly appreciated.
    Rgds
    Sridhar

    I added the tree.updateUI() method call in the finished() method. This renders the children (Yipee!).
    But now I have a new problem. If I collapse and again expand a node, I get a NPE. (I see all the child nodes but a exception is still thrown) The exception happens after my treeWillExpand() and treeExpanded() method implementations. So no probs in my code.
    If you know of a solution, pleeease let me know.
    TIA
    Sridhar
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at javax.swing.plaf.basic.BasicTreeUI.updateSize(Unknown Source)
    at javax.swing.plaf.basic.BasicTreeUI.toggleExpandState(Unknown Source)
    at javax.swing.plaf.basic.BasicTreeUI.handleExpandControlClick(Unknown Source)
    at javax.swing.plaf.basic.BasicTreeUI.checkForClickInExpandControl(Unknown Source)
    at javax.swing.plaf.basic.BasicTreeUI$MouseHandler.mousePressed(Unknown Source)
    at java.awt.AWTEventMulticaster.mousePressed(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

  • Can we use more than one Help Provider class in a same project in ADF11g

    Hi All,
    There are two help providers i want to use .They are "ResourceBundleHelpProvider","OHW Help Provider"
    In adf-settings.xml file
    <help-provider>
    <help-provider-class>oracle.adf.view.rich.help.ResourceBundleHelpProvider</help-provider-class>
    <property>
    <property-name>baseName</property-name>
    <value>com.symmetry.dashboard.panels.Help</value>
    </property>
    </help-provider>
    if try to register both help providers confliction occurs. Is it possible to register and use more than one help provider.?
    Thanks in advance.:)

    Thanks Frank,
    In adf-settings.xml file
    <help-provider>
    <help-provider-class>oracle.adf.view.rich.help.ResourceBundleHelpProvider</help-provider-class>
    <property>
    <property-name>baseName</property-name>
    <value>com.symmetry.dashboard.panels.Help</value>
    </property>
    </help-provider>
    <help-provider prefix="RB_">
    <help-provider-class>oracle.help.web.rich.helpProvider.OHWHelpProvider</help-provider-class>
    <property>
    <property-name>ohwConfigFileURL</property-name>
    <value>/myHelpset/config.xml</value>
    </property>
    <property>
    <property-name>baseURI</property-name>
    <value>http://127.0.0.1:7101/Dashboard_workflow/myHelpset/%3c/value>
    </property>
    </help-provider>
    I differentiated the help providers with the "prefix" attribute in the <help-provider> tag. So now confliction is not occuring between those.
    I used this prefix in the "helpTopicId" property of the adf components like "input text box" . I got the result. :)

  • Using single version DPS for college class

    Hi,
    I teach media design at a four-year university and we'd like to develop an iPad app for a special topics class using the single version DPS.
    We want to make sure this is workable BEFORE we spend the $400 for the app.
    I've created several test folios using CS5.5 with updated folio builder and overlay creator and can only view them sporadically on the Adobe Content Viewer on my iPad (4). None of the other students (older iPads) can view them at all.
    It will be necessary for at least three of us to be able to preview folios in content viewer.
    Will the single version DPS provide us with a way to preview on multiple iPads? We need to do a lot of proofing and reviewing BEFORE we publish this app.
    The students are REALLY excited about doing this but I need to make sure it will work before we spend the money.
    We just want to create ONE single publication but again we need to make sure we can preview every article to make sure the interactivity behaves the way we intended and to copyedit.
    I can't seem to get an answer for this by calling Adobe or chatting with a live rep.
    Thanks so much.

    In your copy of InDesign 5.5 go to the folio builder and click on the "About..." submenu item" to see what version you are running. Update if you are not using version "12.2.2.20120504." A good resource is at the top of the DPS forum -- "Can you update Adobe DPS?" That website will tell you what builder version you should be running, what tools and viewers you need.
    There are discussisons on here what keeping the DPS up-to-date and the best practices to follow.
    To answer your question, I don't think you need to delete and reinstall. Your iTunes and iPad should be telling you if there is an update to the content viewer.

  • Compiler error when useing switch statements in an inner class

    I have defined several constants in a class and want to use this constans also in an inner class.
    All the constants are defined as private static final int.
    All works fine except when useing the switch statement in the inner class. I get the compiler error ""constant expression required". If I change the definition from private static final to protected static final it works, but why?
    What's the difference?
    Look at an example:
    public class Switchtest
       private static final int AA = 0;     
       protected static final int BB = 1;     
       private static int i = 0;
       public Switchtest()
          i = 0; // <- OK
          switch(i)
             case AA: break; //<- OK, funny no problem
             case BB: break; //<- OK
             default: break;
      private class InnerClass
          public InnerClass()
             i = 0; // <- OK: is accessible
             if (AA == i) // <- OK: AA is seen by the inner class; i  is also accessible
                i = AA + 1;
             switch(i)
                case AA: break; // <- STRANGE?! Fail: Constant expression required
                case BB: break; // <- OK
                default: break;
    }Thank's a lot for an explanation.

    Just a though:
    Maybe some subclass of Switchtest could decalare its own variable AA that is not final, but it can not declare its own BB because it is visible from the superclass. Therefore the compiler can not know for sure that AA is final.

  • Using EveryNCallback function with a C++ class (not VB)

    Hello all,
    I am trying to incorporate one of the ANSI C examples into my code which contains C++ classes. I receive errors because of having to declare the EveryNCallback and DoneCallback functions as static to keep their C function signature. This of course is not allowable when using these functions as members of a class. Could anyone help please?
    Best,
    Paolo

    Firstly, thank you for the help. I have attempted to code the advice you gave but it still does not seem to compile properly. Can you suggest what is wrong with my code please?
    Here is the code I am trying to configure:
    forceDriver.h
    static int32 CVICALLBACK static_callback(TaskHandle taskHandle, int32 everyNsamplesEventType, uInt32 nSamples, void* callbackData);
    int32 EveryNCallback(TaskHandle taskHandle, int32 everyNsamplesEventType, uInt32 nSamples);
    int32 DoneCallback(TaskHandle taskHandle, int32 status, void *callbackData);
    forceDriver.cpp
    DAQmxErrChk (DAQmxRegisterEveryNSamplesEvent(taskHandle,DAQmx_Val_Acquired_Into_Buffer,2500,0,&forceDriver::static_callback,panel));
    **START TASK**
    int32 forceDriver::EveryNCallback(TaskHandle taskHandle, int32 everyNsamplesEventType, uInt32 nSamples)
           panel->(member_function);
    int32 CVICALLBACK forceDriver::static_callback(TaskHandle taskHandle, int32 everyNsamplesEventType, uInt32 nSamples, void* callbackData)
    forceDriver* static_object = static_cast<forceDriver*>(callbackData);
    return static_object->EveryNCallback(taskHandle, everyNsamplesEventType, nSamples);
    where panel is the object I have created. 

  • Should I use a SwingWorker or SwingUtilities.invokeLater() to update my UI?

    Are there specific situations where you want to use method above the other? This whole swing concurrency is very new to me, and I don't really know where to begin.

    When executing long running code you don't want the GUI to freeze. Therefore you have two things to be concerned about. First, you want the long running task to execute in a separate Thread. Secondly, when you need to update the GUI from this code you need to make sure the code executes on the Event Dispatch Thread (EDT).
    You can code this manually by creating a separate Thread and then use SwingUtilities.invokeLater() when necessary.
    A SwingWorker tries to simplify this process by having a simple API where you can add code that executes on a separate Thread or where you can add code that executes on the EDT.
    So in the case of managing long running tasks, the end result should be the same.
    Hwever, there are times when I know code is already executing on the EDT, but I sometimes use invokeLater(..) to force my code to the end of the EDT. This is used in special situations when code doesn't execute in the order you want.
    For example, I've tried to add a FocusListener to a JFormattedTextField to "select the text" when it gains focus. The problem is the the UI also adds a FocusListener. Because of the way listeners are handled the last listener added to the component executes first. Therefore, using the invokeLater() forces my listener code to execute last.
    You can try this code to see what I mean:
    KeyboardFocusManager.getCurrentKeyboardFocusManager()
         .addPropertyChangeListener("permanentFocusOwner", new PropertyChangeListener()
         public void propertyChange(final PropertyChangeEvent e)
              if (e.getNewValue() instanceof JTextField)
                   //  invokeLater needed for JFormattedTextField
                   SwingUtilities.invokeLater(new Runnable()
                        public void run()
                             JTextField textField = (JTextField)e.getNewValue();
                             textField.selectAll();
    });Edited by: camickr on Mar 5, 2011 2:36 PM

  • Using stored parameter from data control class with stacked bar-graph

    Hi folks,
    I'm relatively new to ADF & EJB so I want to apologise in advance if this question seems rudimentary to many of you.
    Edit:  I should have mentioned that I'm using JDeveloper 11.1.1.5
    I'm having a hard time determining how to retrieve the value from a variable to be assigned to a property of the bar graph I'm trying to display on my JSF page.
    I have tried to briefly summarise the logic below for reference.
    I have a data control class (ActivityChart) that includes a method "getActivityDetail" returns a List of custom Objects (ActivityDTO) that are the underlying data for my bar graph.
    public class ActivityChart {
        private Double axisScale;
        public ActivityChart() {
            super();
            axisScale = 0.0;
        public List<ActivityDTO> getActivityDetail(List<String> businessUnits) {
            List<ActivityDTO> returnNewList = new ArrayList<ActivityDTO>();
            List<TransactionDTO> dataList = new ArrayList<TransactionDTO>();
            TransactionSessionBean transBean = lookupTransactionSessionBean();
            if (businessUnits != null && !businessUnits.isEmpty()){
                dataList = transBean.getActivityData(SystemUtil.getCurrentUser(), businessUnits);           
                returnNewList = processTransactions(dataList);
                axisScale = calcAxisScale(returnNewList);
            return returnNewList;
    ...The TransactionDTO object is basically a mirror of the entity object to store the fields from the queried db transactions.
    The ActivityDTO object contains a String value (x-axis label) and 3 Double values for the values required for the bar graph.
    What I'm trying to do is dynamically set the scale for the 2 y-axes (I'm using a dual-axis stacked bar graph) because the auto calculated values are not aligned.
    Right now I've got the two relevant elements of the bar graph hard-coded with a specific axis value:
    <dvt:y1Axis axisMaxAutoScaled="false" axisMaxValue="100.0"/>
    <dvt:y2Axis axisMaxAutoScaled="false" axisMaxValue="100.0"/>.
    The value I want to use for the Y-axis is calculated and stored in the "axisScale" variable in the above class.
    Really at a loss of how to move forward from here.
    Would very much appreciate any guidance/direction offered.
    Thanks,
    Karim
    Edited by: 973742 on Nov 28, 2012 8:12 AM

    Looks like I may have found the answer!
    I had to set up the variable in the bindings for the page and then reference the variable from the binding and add the property inputValue.
    ie. value="#{bindings.axisScale.inputValue}"

  • Using Get Data From Aggregation event class in SQL Profiler - SSAS 2012

    Hi,
    I'd like to understand better the use of the Get data from aggregation event class in SQL Profiler to monitor a MDX query and which info provide. Fe, does it return the MDX query? Is it possible to use this event class in order to monitor MDX query vs a
    Tabular model?
    In the TechNet documentation, this event class is handled briefly.
    Thanks

    Hi pscorca,
    This event is raised when the storage engine reads data from an aggregation, it may have a negative impact on performance when turned on. If you need to monitor SSAS instance status, we can also use dynamic management view:
    Use Dynamic Management Views (DMVs) to Monitor Analysis Services:
    http://msdn.microsoft.com/en-us/library/hh230820.aspx
    Regards,
    Elvis Long
    TechNet Community Support

Maybe you are looking for