Delicate ProgressMonitor/ event handling problem

Hi,
I have a delicate ProgressMonitor / event handling problem.
There exists some solution on similiar problems here in the forums, but no solution to my special problem, hope anybody can help me out.
I have a rather big project, an applet, that I've written a separate JarLoader class that will load specific jar's if the ClassLoader encounter a unloaded class, all ok so far.
But, during loading, I would like to display a ProgressBar. And here is the problem. If my custom ClassLoader intercepts a findClass -request that needs to load the class from a jar from a normal thread, this is no problem, but if the ClassLoader intercepts a findClass that needs loading a jar when inside the EventQueue -thread, this is becomming tricky!
The catch is that an event posted on the EventQueue finally needs a class that needs to be loaded, but I cannot dispatch a thread to do this and end that particular event before the class itself is loaded.
So how do I hold the current EventQueue -event needing a jar -load, Pop up a ProgressBar, then process events in the EventQueue to display the ProgressBar and update repaints in it? then return from the event that now have loaded needed class-files.
I've tried a tip described earlier in the forums by trying to handle events with this code when loading the Jar:
    /** process any waiting events - use during long operations
     * to update UI */
    static public void doEvents() {
        // need to derive from EventQueue otherwise
        // don't have access to protected method dispatchEvent()
        class EvtQueue extends java.awt.EventQueue {
            public void doEvents() {
                Toolkit toolKit = Toolkit.getDefaultToolkit();
                EventQueue evtQueue = toolKit.getSystemEventQueue();
                // loop whilst there are events to process
                while (evtQueue.peekEvent() != null) {
                    try {
                        // if there are then get the event
                        AWTEvent evt = evtQueue.getNextEvent();
                        // and dispatch it
                        super.dispatchEvent(evt);
                    catch (java.lang.InterruptedException e) {
                        // if we get an exception in getNextEvent()
                        // do nothing
        // create an instance of our new class
        EvtQueue evtQueue = new EvtQueue();
        // and call the doEvents method to process the events.
        evtQueue.doEvents();       
    }Then, the loader checks
java.awt.EventQueue.isDispatchThread()to see if its' inside the eventqueue, and runs doEvents after updating the ProgressMonitor with new setProgress and setNote values.
More precise;
The loader is loading the jar like this:
(this is pseudo code, not really usable, but outlines the vital parts)
public void load() {
  monitor = new ProgressMonitor(null, "Loading " + jarName, ""+jarSize + " bytes", 0, jarSize);
  monitor.setMillisToDecideToPopup(0);
  monitor.setMillisToPopup(0);
  // reading jar info code here ...
  JarEntry zip = input.getNextJarEntry();
  for (;zip != null;) {
     // misc file handling here... total = current bytes read
     monitor.setProgress(total);
     monitor.setNote(note);
     if (java.awt.EventQueue.isDispatchThread()) {
        doEvents();
     zip = input.getNextJarEntry();
  monitor.close();
}When debugging doEvents(), there is never any events pending in peekEvents(), even if I tries to put a invokeLater() to run the setProgress on the monitor, why? If it had worked, the doEvents() code would have saved my day...
So, this is where I'm totally stuck...

Just want to describe how I did this using spin from http://spin.sourceforge.net
This example is not pretty, but it can probably help others understanding spin. Cancelling the ProgressMonitor is not implemented, but can easily be done by checking on ProgressMonitor.isCanceled() in
the implementation code.
First, I create a bean for displaying and run a ProgressMonitor:
Spin requires an Interface and an Implementation, but that's just nice programming practice :-)
import java.util.*;
public interface ProgressMonitorBean {
    public void start(); // start spinning
    public void cancel(); // cancel
    public int getProgress(); // get the current progress value 
    public void setProgress(int progress); // set progress value
    public void addObserver(Observer observer); // observer on the progressValue
}Then, I created the implementation:
import java.util.*;
import javax.swing.ProgressMonitor;
import java.awt.*;
public class ProgressMonitorBeanImpl extends Observable implements ProgressMonitorBean {
    private ProgressMonitor monitor;
    private boolean cancelled;
    private int  progress = 0;
    private int  currentprogress = 0;
    public ProgressMonitorBeanImpl(Component parent, Object message, String note, int min, int max) {
        monitor = new ProgressMonitor(parent, message, note, min, max);
        monitor.setMillisToDecideToPopup(0);
        monitor.setMillisToPopup(0);       
    public void cancel() {
        monitor.close();
    public void start() {
        cancelled = false;
        progress = 0;
        currentprogress = 0;
        while (progress < m_cMonitor.getMaximum()) {
            try {
                synchronized (this) {
                    wait(50); // Spinning with 50 ms delay
                if (progress != currentprogress) { // change only when different from previous value
                    setChanged();
                    notifyObservers(new Integer(progress));
                    monitor.setProgress(progress);
                    currentprogress = progress;
            } catch (InterruptedException ex) {
                // ignore
            if (cancelled) {
                break;
    public int getProgress() {
        return progress;
    public void setProgress(int progress) {
        this.progress = progress;
}in my class/jarloader code, something like this is done:
public void load() {
  ProgressMonitorBean monitor = (ProgressMonitorBean)Spin.off(new ProgressMonitorBeanImpl(null, "Loading " + url,"", 0, jarSize));
  Thread t = new Thread() {
    public void run() {
      JarEntry zip = input.getNextJarEntry();
      for (;zip != null;) {
        // misc file handling here... progress = current bytes read
     monitor.setProgress(progress);
  t.start(); // fire off loadin into own thread to do time consuming work
  monitor.start(); // this will spin events on monitor and block until progress = max
  monitor.cancel(); // Just make sure ProgressMonitor is closed
}The beautiful thing here is that Spin is taking care of weither the load() is inside the dispatch thread or not, making the code much simpler and cleaner to understand.
The ProgressMonitorBeanImplementation could been made much nicer and more complete, but I was in a hurry to check if it worked out. And it did! This will be applied on a lot of gui -components that blocks the event-queue in our project, making it much more responsive.
Hope this will help others in similiar situations! Thanks again svenmeier for pointing me to the spin -project.

Similar Messages

  • GUI event handling problems appear in 1.4.1 vs. 1.3.1?

    Hi,
    Has anyone else experienced strange event handling problems when migrating from 1.3.1 to 1.4.1? My GUI applications that make use of Swing's AbstractTableModel suddenly don't track mouse and selection events quickly anymore. Formerly zippy tables are now very unresponsive to user interactions.
    I've run the code through JProbe under both 1.3 and 1.4 and see no differences in the profiles, yet the 1.4.1 version is virtually unusable. I had hoped that JProbe would show me that some low-level event-handling related or drawing method was getting wailed on in 1.4, but that was not the case.
    My only guess is that the existing installation of 1.3.1 is interfering with the 1.4.1 installation is some way. Any thoughts on that before I trash the 1.3.1 installation (which I'm slightly reluctant to do)?
    My platform is Windows XP Pro on a 2GHz P4 with 1GB RAM.
    Here's my test case:
    import javax.swing.table.AbstractTableModel;
    import javax.swing.*;
    import java.awt.*;
    public class VerySimpleTableModel extends AbstractTableModel
    private int d_rows = 0;
    private int d_cols = 0;
    private String[][] d_data = null;
    public VerySimpleTableModel(int rows,int cols)
    System.err.println("Creating table of size [" + rows + "," + cols +
    d_rows = rows;
    d_cols = cols;
    d_data = new String[d_rows][d_cols];
    int r = 0;
    while (r < d_rows){
    int c = 0;
    while (c < d_cols){
    d_data[r][c] = new String("[" + r + "," + c + "]");
    c++;
    r++;
    System.err.println("Done.");
    public int getRowCount()
    return d_rows;
    public int getColumnCount()
    return d_cols;
    public Object getValueAt(int rowIndex, int columnIndex)
    return d_data[rowIndex][columnIndex];
    public static void main(String[] args)
    System.err.println( "1.4..." );
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    Dimension size = new Dimension(500,500);
    panel.setMinimumSize(size);
    panel.setMaximumSize(size);
    JTable table = new JTable(new VerySimpleTableModel(40,5));
    panel.add(table);
    window.getContentPane().add(panel);
    window.setSize(new Dimension(600,800));
    window.validate();
    window.setVisible(true);
    Thanks in advance!!
    - Dean

    Hi,
    I've fixed the problem by upgrading to 1.4.1_02. I was on 1.4.1_01.
    I did further narrow down the symptoms more. It seemed the further the distance from the previous mouse click, the longer it would take for the table row to highlight. So, clicking on row 1, then 2, was much faster than clicking on row 1, then row 40.
    If no one else has seen this problem -- good! I wouldn't wish the tremendous waste of time I've had on anyone!
    - Dean

  • Labview slider event handling problems - revisited

    This topic asked a question that was very close to a problem I am having:
    Labview slider event handling problems
    That is, how do I, using an event structure and/or other means, only read out the value of a slider control after the value change is finalized?
    The extra constraint I'd like to place on this, which I believe will invalidate the answer given in the thread above, is that my slider control also has a digital display which can also be used to change the value without ever using the mouse. I cannot look for a value change followed by a mouse-up event if the mouse was not used to change the value.
    Any ideas how this might be accomplished? FWIW, I am using LabVIEW 7.0

    Each and every incremental value-change event generated by the movement of the slider is still detected and queued up for use by the event structure and the event structure loop wades through them all before it's done.
    I have come up the attached "fix" (LV v7.0) for this problem. While it is not as clean a solution as I had hoped it would be, it's the best I can manage given what LabVIEW offers me to work with and it does work in the situation where I need to use it.
    Now, within the Finalize Slider Events subVI, I'm keeping track of the most-recent values seen by the subVI, checking to see if they have changed, and reporting out that fact. That gives me a Changed/Not-Changed bit within the event case that I can use to control what code then gets executed. If the event case is just playing catch-up to the real value of the control, I can now see that fact and ignore it.
    In this version I've also dumped the variant output and limited the VI to using DBL values. I decided it added complication to something that was too complicated already and I wanted the output terminals for other purposes anyway (reporting of the correct "OldVal" of the control).Message Edited by Warren Massey on 04-28-2005 03:56 AM
    Attachments:
    slider_events[5].llb ‏77 KB

  • BSP extension "download" - event handling problem

    Folks,
    First of all, I apologize if the answer is already out there, but I spent quite some time to find the solution for my problem but finally gave up:
    I implemented the Download extension from Brian's and Tom's book. Since I am using an MVC based app, I put the event handling in the DO_HANDLE_EVENT of a controller instead of the OnInputProcessing event of a page. Here's how my app is designed:
    I have a main controller that has an execute button to trigger a data selection based on some selection criteria. The result of this selection is displayed by means of a subcontroller with tableviews that are wrapped into my “zdownload” extension. Everything works fine: I make my selections, execute the app through the button of the main controller and get my result shown in the tableviews. I push the download icon, select my file format (XLS, HTML etc), get the dialog to choose whether to download or to display the file, perfect!
    But now – after I processed the download successfully - if I click the execute button in the main controller again, I still get the download dialog. It looks like the created event for the download does not get cleared. As I mentioned, I searched through SDN, but all I found were referrals to the call of DISPATCH_INPUT( ) in DO_REQUEST of the main controller, but unfortunately this one is already implemented.
    Any ideas?
    Thanks,
    Guenther

    There is an attribute of the download extension called display_url. You pass a value to the extension telling it what cached URL contains the binary content for your download.  if this display_url attribute has a value assigned to it, then the element will render an iFrame to call the URl.  However if the display_url attribute is empty, it won't render the iFrame.  I suspect that you have a stateful application and after your download event you aren't clearing whatever field that you pass into the display_url attribute.

  • Event handler problems

    Hi,
    I'm having problems with a event handler that I'm trying to create.
    I currently have 2 event handlers, one of which needs to only happen when Shift + a key is pressed. I currently have:
    function keypressedHandler(event:KeyboardEvent):void {      if ((event.shiftKey) + (event.keyCode == 81)) {        //something would happen      } } 
    So my question is how can I get the shift function to work? It doesn't matter if it isn't shift but Alt or Ctrl would be the alternatives.
    Any help would be great,
    Thanks,

    You need the ampersand (&) instead of the plus sign to use the logical AND:
    stage.addEventListener( KeyboardEvent.KEY_DOWN, keypressedHandler )
    function keypressedHandler(event:KeyboardEvent):void
        if ((event.shiftKey) && (event.keyCode == 65))
            //something would happen     
            trace( "shift and 65" )

  • SBO2004: Event Handling problems

    Hello, all
    I have noticed a very peculiar thing about the way SBO handles events.
    I wrote a handler for the et_VALIDATE event on an EditText item (Sales Quotation->Customer) which does nothing but waits for two minutes. Then I performed the following experiment:
    Opened a sales quotation from in the Add mode, chose a Customer and added an item. Them I put the cursor into the Cusotmer field and pressed "Add". As a result, my event handler fired, so SBO was "frozen" for two minutes. But when the handler had completed nothing happened. The quotation wasn't added, although I didn't set BubbleEvent to false in the eventhandler.
    However, when I reduced the wait time to 30 seconds in the event handler everything started to work as it should: after completion of the eventhandler the quotation got added.
    Looks like if the handler of the preceding event (VALIDATE) executes for too long the following event (ITEM_PRESSED) may not fire at all...
    I this a correct behavior?
    Thanks in advance,
    Anton
    PS: I was testing in SBO2004

    Please update your system. Version 2004 is no longer supported.
    Hello, Vitor
    I know this, but I can't update soon. So I hope somebody can either confirm this problem or suggest a solution/workaround. But OK, I will check this in SBO2007.
    Anton

  • Button event handler problem

    Hello,
    I need to add an Event handler to a button on my JSP page. The page refreshes very three seconds for other use.
    First, I added the following segment to the page.
    <head>
    <title>Event handler test</title>
    <script type="text/javascript">
    <!--
    function funAdd()
    alert("Your name is already in the list.");
    //-->
    </script>
    <meta http-equiv="refresh" content="3">
    </head>
    <input type = "button" name = "add" value = "Add" onclick="funAdd()" />
    Every time I clicked the Add button, the alert message appeared. It showed the expected result.
    Then, I replaced alert("Your name is already in the list."); with
    <%
    JOptionPane.showMessageDialog(null, "Your name is already in the list.", "Error message", JOptionPane.ERROR_MESSAGE);
    %>
    in funAdd().
    But, the error message showed automatically every three seconds when the page refreshed without clicking the Add button.
    Does any one know the reason, and how to solve the problem?
    Thanks in advance.
    Dan

    You said it yourself, you refresh your page each 3 seconds so each 3 seconds you do a request to your server where you show a messagedialog.

  • Multiple JComboBox Event Handling Problem

    Hi, guys
    I am a newbie in Java. I need to create three JComboBox, say date, month and year and a JButton "submit". After I select the entries from the three JComboBox, I click the "search" button to display something in terms of the information I selected, but I have no idea how to write the actionPerformed( ActionEvent evt) to deal with the problem. Can anyone give me some hint?
    Any help would be appreciated.

    If you are asking how to write a basic event handler for when your button is pressed, RTM.
    http://java.sun.com/docs/books/tutorial/uiswing/events/index.html

  • UIcommand's event handling problem

    Hi experts,
    I'm developing a UIcommand, this UIcommand need render a TableView UI component.
              TableView LIST_TABLE_UI = new TableView("LIST_TABLE_UI",
                   new DefaultTableViewModel(list_tablemodel.getData(),list_tablemodel.columnNames));
              LIST_TABLE_UI.setDesign(TableViewDesign.ALTERNATING);
              LIST_TABLE_UI.setHeaderVisible(true);
              LIST_TABLE_UI.setFooterVisible(true);
              LIST_TABLE_UI.setFillUpEmptyRows(true);
              LIST_TABLE_UI.setNavigationMode(TableNavigationMode.BYLINE);
              LIST_TABLE_UI.setSelectionMode(TableSelectionMode.MULTISELECT);
              LIST_TABLE_UI.setVisibleFirstRow(1);
              LIST_TABLE_UI.setVisibleRowCount(list_tablemodel.getData().size());
              LIST_TABLE_UI.setRowCount(4);
              LIST_TABLE_UI.setSelectionMode(TableSelectionMode.MULTISELECTWITHOPTIONS);
              LIST_TABLE_UI.setOnRowSelection("onRowSelClick");
              LIST_TABLE_UI.setNavigationMode(TableNavigationMode.BYPAGE);
              LIST_TABLE_UI.setOnNavigate("tableNavigation");
    My problem is regarding the event handling. When I select a row, an exception is thown:
    Caused by: com.sapportals.htmlb.page.PageException: Eventhandler- "onRowSelClick" not found!
    I've try to add this method, but problem remains. Can anybody help??Points will definitely be rewarded for helpful anwsers, many tks!

    Hi Julio,
    Thank you for your reply, so is there anyway to do this? What I need is use TableView in my UI command, tks!
    Best Regards,
    Xiaoming Yang

  • Event Handling problem

    Hello everyone.
    i am trying to handle events in the item master date form (150) in order to hide the Item Cost. It is working fine with most of the time using only the UI api. However if doing the following actions, the events are not processed by the application anymore.
    1- Start SBO (2005 sp1 pl18)
    2- Login
    3- Start my add-on with vb.net
    4- Go into the item master data.. (handling events correctly)
    5- Close item master data.
    6 -Go into another form
    7- Close the other form
    8- Go back into item master data --> no events handling is done
    Any ideas???
    Thank you
    Simon
    Source code.
    Public Class ItemCostControl
        Private WithEvents SBO_Application As SAPbouiCOM.Application
        ' Declare Event Filter
        Public oFilters As SAPbouiCOM.EventFilters
        Public oFilter As SAPbouiCOM.EventFilter
        Private Const itemCostField As String = "64"
        Private Const itemCostColumn As String = "22"
        Private Const itemCostGrid As String = "28"
        Private Const formItemMaster As String = "150"
        Private Sub SetApplication()
            '// Use an SboGuiApi object to establish the connection
            '// with the application and return an initialized appliction object
            Dim SboGuiApi As SAPbouiCOM.SboGuiApi
            Dim sConnectionString As String
            SboGuiApi = New SAPbouiCOM.SboGuiApi
            sConnectionString = Environment.GetCommandLineArgs.GetValue(1)
            '// connect to a running SBO Application
            SboGuiApi.Connect(sConnectionString)
            '// get an initialized application object
            SBO_Application = SboGuiApi.GetApplication()
        End Sub
        Private Sub SetFilters()
            '// Create a new EventFilters object
            oFilters = New SAPbouiCOM.EventFilters
            oFilter = oFilters.Add(SAPbouiCOM.BoEventTypes.et_FORM_ACTIVATE)
            oFilter = oFilters.Add(SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
            oFilter = oFilters.Add(SAPbouiCOM.BoEventTypes.et_MENU_CLICK)
            '// assign the form type on which the event would be processed
            oFilter.AddEx("150")
            SBO_Application.SetFilter(oFilters)
        End Sub
        Public Sub New()
            '// set SBO_Application with an initialized application object
            SetApplication()
            '// set SBO_Application with an initialized EventFilters object
            SetFilters()
        End Sub
        Private Sub SBO_Application_ItemEvent(ByVal FormUID As String, ByRef pVal As SAPbouiCOM.ItemEvent, ByRef BubbleEvent As Boolean) Handles SBO_Application.ItemEvent
            Dim oForm As SAPbouiCOM.Form
            System.Diagnostics.Debug.WriteLine("Item Event for " + FormUID)
            If pVal.FormType <> 0 And pVal.BeforeAction = False Then
                Select Case pVal.EventType
                    Case SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED
                        System.Diagnostics.Debug.WriteLine("Item Pressed")
                        hideField(pVal.FormType, pVal.FormTypeCount, itemCostField)
                        hideColumn(pVal.FormType, pVal.FormTypeCount, itemCostGrid)
                    Case SAPbouiCOM.BoEventTypes.et_FORM_ACTIVATE
                        System.Diagnostics.Debug.WriteLine("Form Activate")
                        hideField(pVal.FormType, pVal.FormTypeCount, itemCostField)
                        hideColumn(pVal.FormType, pVal.FormTypeCount, itemCostGrid)
                    Case SAPbouiCOM.BoEventTypes.et_FORM_LOAD
                        System.Diagnostics.Debug.WriteLine("Form Load")
                        hideField(pVal.FormType, pVal.FormTypeCount, itemCostField)
                        hideColumn(pVal.FormType, pVal.FormTypeCount, itemCostGrid)
                End Select
            End If
        End Sub
        Private Sub SBO_Application_MenuEvent(ByRef pVal As SAPbouiCOM.MenuEvent, ByRef BubbleEvent As Boolean) Handles SBO_Application.MenuEvent
            '// in order to activate your own forms instead of SAP Business One system forms
            '// process the menu event by your self
            '// change BubbleEvent to True so that SAP Business One won't process it
            Dim oForm As SAPbouiCOM.Form
            If pVal.BeforeAction = False Then
                hideField(formItemMaster, 1, itemCostField)
                hideColumn(formItemMaster, 1, itemCostGrid)
            End If
        End Sub
        Public Sub hideField(ByVal FormType As String, ByVal FormTypeCount As Integer, ByVal fieldNo As String)
            Dim oForm As SAPbouiCOM.Form
            oForm = SBO_Application.Forms.GetForm(FormType, FormTypeCount)
            oForm.Items.Item(fieldNo).Left = 3000
            oForm.Items.Item(fieldNo).Visible = False
        End Sub
        Public Sub hideColumn(ByVal FormType As String, ByVal FormTypeCount As Integer, ByVal fieldNo As String)
            Dim oForm As SAPbouiCOM.Form
            Dim oGrid As SAPbouiCOM.Matrix
            Dim oItem As SAPbouiCOM.Item
            oForm = SBO_Application.Forms.GetForm(FormType, FormTypeCount)
            oItem = oForm.Items.Item(fieldNo)
            oGrid = oItem.Specific
            If oGrid.Columns.Item(itemCostColumn).Visible = True Then
                oGrid.Columns.Item(itemCostColumn).Visible = False
                oGrid.Columns.Item(itemCostColumn).Width = 0
            End If
        End Sub
    End Class

    Hi, Simon!
    Try setting filters like that:
    oFilter = oFilters.Add(SAPbouiCOM.BoEventTypes.et_FORM_ACTIVATE)
    '// assign the form type on which the event would be processed
    oFilter.AddEx("150")
    oFilter = oFilters.Add(SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
    '// assign the form type on which the event would be processed
    oFilter.AddEx("150")
    oFilter = oFilters.Add(SAPbouiCOM.BoEventTypes.et_MENU_CLICK)
    '// assign the form type on which the event would be processed
    oFilter.AddEx("150")
    I suppose that the setting method you used, was filtering only et_MENU_CLICK for the 150-form. But other events (et_FORM_ACTIVATE, et_ITEM_PRESSED) were handling for all forms...
    hth,
    Aleksey

  • Rather complicated (possibly!) threading/event handling problem...

    OK, so here's a good question to ask for my first post to this site!
    My current "project" is a GUI applet that does real-time interactions on a set of objects and user input. I'm using double buffering, event handling (from the keyboard) and multiple threads to handle the categories of "user input and graphics" and "world state updating." Here is a rough overview of how the program is layed out:
    // keyboard input status class
    class Keyboard extends KeyListener {
       static int[] code = new int[7];            // contains keycodes of interesting keys
       static boolean[] status = new boolean[7];     // status of keys (true=pressed)
       static boolean getStatus(int key) {
          return status[key];
       void keyPressed(KeyEvent e) {
          for(int i = 6; i >= 0; i--)
             if(code[i] == e.code)
                status[i] = true;
       void keyReleased(KeyEvent e) {
          for(int i = 6; i >= 0; i--)
             if(code[i] == e.code)
                status[i] = false;
    // main program applet
    class Program extends Applet implements Runnable {
       static Thread thread;      // main thread of applet
       static Image buffer;         // double buffer for offscreen rendering
       static boolean running;  // flag to indicate status of applet
       void init() {
          buffer = createImage(500, 500);
          // other initializations
       void destroy() {
          // other disposes
       void start() {
          running = true;
          thread = new Thread(this);
          thread.start();
          addKeyListener(new Keyboard());   // begin receiving input
       void stop() {
          running = false;
          if(thread != Thread.currentThread())
             thread.join();    // wait for thread to die before continuing
       void run() {
          double paintTimer = 0;   // timer to suspend painting to buffer until necessary
          double dt = 0;       // difference in time between loops
          while(running) {
             // update timing stuff (dt and paintTimer)
             // update world status
             paintTimer -= dt;      // to decrement painting timer
             if(paintTimer <= 0) {
                paintTimer = 1.0 / fps;    // reset paint timer based on current fps setting
                synchronized(syncObject) {
                   // paint world to buffer
                   repaint();
             Thread.yield();  // to yield time to painting and user input thread
       // this method is only called by the internal thread within the applet
       //  that is responsible for painting and event handling
       void paint(Graphics g) {
          // make sure painting to screen won't conflict with thread that's drawing on buffer!
          synchronized(syncObject) {
             g.drawImage(buffer, 0, 0, null);  // do double buffering...paint buffer to screen
    }So the end result is that it works fine some of the time, but every once in awhile I'll get these strange results where it'll seem as if the internal thread that handles graphics and input will get bogged down or stop responding normally, even with the Thread.yield() call from the main applet thread. I'll get results where the world will continue to be updated correctly, but the user input and onscreen rendering freeze in a particular state for a matter of seconds, and then it seems to regain control for a brief few milliseconds (hence I'll get a quick screen refresh and keyboard state change), and then it'll freeze again. Once this starts happening somewhere in the middle of execution, it continues to happen throughout that runtime session. Sometimes when I force-close the appletviewer I'll get weird native runtime exceptions that seem to occur within Sun's keyboard input manager.
    Almost always it'll run perfectly for many minutes, and then all of a sudden it'll start to freeze up. Every once in awhile it freezes almost immediately after startup. I've run some testcases on it and am pretty confident it has nothing to do with the synchronization or the fact that I create a new applet thread every time the applet is restarted dynamically. Is it something happening within the event thread of the applet that I'm not aware of? Or is it something wrong with the flow of my code? Thanks for any input or help you can give! I'll be happy to send more details if needed.
    Zach

    right before your repaint, putSystem.out.println("Is EDT? "+SwingUtilities.isEventDispatcherThread());if its printing false, then you need to do SwingUtilities.invokeLater( ... );
    and put GUI updating code in the invoke later.

  • Event handling problems

    Am quite unsure about how to add in event handling into my GUI for my assignment to make a Game. Am trying to begin by getting the exit button (button2) to close the window when its clicked. Thing ive gone a bit off the mark. Can anyone help?
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.Random;
    public class Game extends JFrame
        public static void main (String [] args)
        new Game();
        Random generator = new Random();
        int runningTotal = generator.nextInt(100);
        String number = Integer.toString(runningTotal);
    private JButton button2;
    public Game()
        this.setSize(400,200);
        this.setTitle("Nim");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         panel aPanel = new panel();
        this.add(aPanel);
       // ClickListener c1 = new ClickListener();
      //  button1.addActionListener(c1);
      //  aPanel.add(button1);
        this.setVisible(true);
    class panel extends JPanel
       public panel()
        JLabel label1 = new JLabel("Number of Pieces");
        JTextField text1 = new JTextField(20);
        text1.setText(number);
        this.add(label1);
        this.add(text1);
        JLabel label2 = new JLabel("Your pick");
       ClickListener c1 = new ClickListener();
        JTextField text2 = new JTextField(5);
        JButton button1 = new JButton("OK");
        JButton button2 = new JButton ("EXIT");
        button2.addActionListener(c1);
        JLabel label3 = new JLabel("Computers Pick");
        JTextField text3 = new JTextField(5);
        JLabel label4 = new JLabel("Current Total");
        JTextField text4 = new JTextField(30);
        text4.setEditable(false);
        JLabel label5 = new JLabel("               Winner");
        JTextField text5 = new JTextField(20);
       // ButtonListener b1 = new ButtonListener();
        this.add(label2);
        this.add(text2);
        this.add(button1);
        this.add(label3);
        this.add(text3);
        this.add(label4);
        this.add(text4);
        this.add(label5);
        this.add(text5);
        this.add(button2);
    private class ClickListener
            implements ActionListener
        private int clickCount = 0;
        public void actionPerformed (ActionEvent e)
            if (e.getSource()== button2)
                System.exit(0);
    [ /code]
    any help greatly appreciated, I think im putting thigs in the wrong order. at the moment my GUI comes up on the screen but the button I want to do something isn't.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    the button2 in panel's constructor hides the one from Game class
    remove the "JButton" in front of "button2" in its creation statement and everything will work fine

  • Labview slider event handling problems

    Hi,
    I've faced problems while working with sliders, which values are passed to serial device. I am using events, and here is a problem: if i use "Value changed" event and change slider position by moving a mouse, the event is generated a few times (i.e. event is triggered by every single value on a slider). It means, that I have to transmit intermediate values to my serial device in order to set the last one. I tried to change event "Value changed" to "Mouse Up", but there was another problem: the value doesn't change if mouse leaves control element area (i.e., "mouse up" is generated as VI event, not as slider event). It would seem to be OK, but slider position is already changed, and there is no other variable which stores
    value of current slider position! I mean that value and slider position are different and I don't know how to synchronize them. Using "Mouse Up" event for whole VI is not a good solution for me, because I have multiple sliders to control separately.
    How to create non-redudand and efficient slider handling? Any ideas?
    (Please see attached VI example)
    Thank You
    Vitalijus
    Attachments:
    slider_events.vi ‏34 KB

    You need a 2 states machine. First state waits for "Value Changed". Once a change is detected, you know that the user is editing the slider and the mouse is currently used to move the slider. Second state waits for "Mouse Up" to latch the actual value of the slider.
    See http://exchange.ni.com/servlet/ProcessRequest?RHIVEID=101&RNAME=ViewQuestion&HOID=50650000000800000046670000&ECategory=LabVIEW.LabVIEW+General
    where I gave an example not using the event structure but a picture control to detect mouse up and a shift register to detect changed values.
    LabVIEW, C'est LabVIEW

  • Glasspane event handling problem when window is deactivated - activated

    Hello everyone!
    I have a strange problem concerning glasspane used to block user input. The situation is the following:
    I use a JDesktopPane inside a JFrame. In the desktop pane there are placed multiple JInternalFrames. I use a JPanel as glasspane with dummy listeners to block the controls in one of the internal frames. This all works without problems.
    Now if the JFrame becomes inactive (for example the user switches to a browser window) and the I go back to the java application (frame becoming active again), the blocking no longer works. This also happens if a JDialog pops up - so in general this happens if the DesktopPanes host window becomes inactive and active again.
    The glass pane is still there (see it as it is translucent coloured), gets the events (I can see this from debug output in the dummy listeners) but also the controls underneath the glass panes do react now to user input.
    I already tried to watch the JFrame with a WindowListener and reinstall (a new) glass pane when it becomes active again - no effect. Now I am really helpless - maybe there is something very obvious I am doing wrong?
    I appreciate any hint :-) Thank you in advance!

    New problem :-) Also this worked to block the user input, I now get these:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
         at javax.swing.plaf.basic.BasicInternalFrameUI$Handler.forwardMouseEvent(BasicInternalFrameUI.java:1375)
         at javax.swing.plaf.basic.BasicInternalFrameUI$Handler.mouseEntered(BasicInternalFrameUI.java:1327)
         at java.awt.Component.processMouseEvent(Component.java:5497)
         at javax.swing.JComponent.processMouseEvent(JComponent.java:3126)
         at java.awt.Component.processEvent(Component.java:5253)
         at java.awt.Container.processEvent(Container.java:1966)
         at java.awt.Component.dispatchEventImpl(Component.java:3955)
         at java.awt.Container.dispatchEventImpl(Container.java:2024)
         at java.awt.Component.dispatchEvent(Component.java:3803)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
         at java.awt.LightweightDispatcher.trackMouseEnterExit(Container.java:4017)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3874)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
         at java.awt.Container.dispatchEventImpl(Container.java:2010)
         at java.awt.Window.dispatchEventImpl(Window.java:1774)
         at java.awt.Component.dispatchEvent(Component.java:3803)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    Exceptions when I open another JInternalFrame afterwards and then move the mouse into the first internal frame (whose input was blocked by twith the button on glasspane) area.
    Any ideas?

  • Table View MULTI SELECT option and Event handling problems

    Hello All,
    I am facing problem while giving miltselect option in a table view. When i mention multiselect attribute in Select option in table view, i am unable to select all the rows which i want to select,because i have an event onRowSelection event activated so when i select a row then it will automatically go to the event and i am unable to do multiple select.
    Can you guys pl tell me is there any way thtat i can put check boxes in a table column and by that i can get values of row seelct and can perform my subsequent SQL operation.
    Also i am not able to navigate in table view through BYPAGE or BYLINE option. When I click on navigate button then page got refreshed and i lost data.
    One more query guys , can you pl tell me how can i store my internal table values from one event for the another event. I have used EXport/Import but internal table values get refreshed as page got refreshed on event switching/selection.
    Please respond.

    hye rahul.
      as i told you my second solution, will help you . the values remain in the corresponding UI elements.
    For example , you have a drop down and table view. both will trigger events. bind the data of the table at drop down event and bind the dat of the drop down at table event.
    event = cl_htmlb_manager=>get_event( runtime->server->request ).
    CASE event->id.
    when 'dd1'.                   drop down event is fired.
    bind data for drop down
    dd ?= cl_htmlb_manager=>get_data(
                                          request = runtime->server->request
                                          name    = 'dropdown'
                                          id      = dd_id'           " name of the drop down id
    along with drop down bind data for table view
        tbv ?= cl_htmlb_manager=>get_data(
                                          request = runtime->server->request
                                          name    = 'tableView'
                                          id      = 'tbv_id'           " name of the table view
    when 'tbv_id'.                   drop down event is fired.
    bind data for drop down
    dd ?= cl_htmlb_manager=>get_data(
                                          request = runtime->server->request
                                          name    = 'dropdown'
                                          id      = dd_id'           " name of the drop down id
    along with drop down bind data for table view
        tbv ?= cl_htmlb_manager=>get_data(
                                          request = runtime->server->request
                                          name    = 'tableView'
                                          id      = 'tbv_id'           " name of the table view
    This is how data should be binded in case of Stateless application. All the UI elemets must b binded again.. as the global data is refresed again.
    Hope this helps.
    Regards,
    Imran.

Maybe you are looking for

  • Line item Shipping data missing in STO

    Hi, I am making an STO ( same company code ). I have added 4 line items in the STO. For three line items, everything is ok. But when I added the fourth line item , the system gives an information message that sales org data and shipping data could no

  • How do you change the time on the all day setting in the iCal on an iPhone?

    I updated to ios 7 and when I want to put an all day event in. When I set it for an alert, it will only allow it to go off at 9:00 am. How do I change the time of 9:00?

  • JDBC Connection reset by peer: JVM_recv in socket input stream read

    Hey Guys, Has anyone seen this issue? We get this error in our Weblogic app logs at times and no one is able to login to our application. Our database server and SQL server seem fine at a high level. Any ideas what is causing this? com.s1.arch.persis

  • Make It Straight - free plug-in to adjust crooked pics

    At The Depository aka fcp.co http://www.fcp.co/forum/utility/23292-make-it-straight-plug-in-to-adjust-crooked -pics#63866 I published my latest plug-in: On that website you find general advice how to install plug-ins (at fcp.co they offer hundreds!)

  • Drill through from Planning to FDM 11.1.2 Not working

    Hi, I have FDM with Essbase adapter installed, version 11.1.2.0.0. And i have FDM application configured to load data from files to essbase. When in Planning form i am clicking 'drill through' icon on cell with loaded data it opens new window with er