ActionEvent/Setting gui text in an infinite loop

Hi,
I have set up a gui that contains ~ 100 JTextFields and one JTextButton
Pressing the JTextButton on the gui triggers an action event that
1.     establishes a socket connection w/ a server
2.     reads input from the server in an infinite loop
3.     should use the server data to dynamically setText in the various JTextFields found on the gui.
for example, during one iteration of the infinite loop, the data may set the text of JTextField #1 to ?foo? and in a later iteration of the loop, the new data from the input stream may set the text of the same field to something else (e.g. ?bar?). Thus, the gui should show a dynamically changing collection of TextFields after the user presses the JTextButton.
Problem: because of the infinite loop, NONE of the fields is ever updated (see pseudocode below). If I remove the infinite loop and simply have 1 iteration of the block of code within the actionPerformed method, the gui updates properly.
How might I alter the code to a) maintain the server connection, b) continuously read from the input stream and c) have a dynamic update of the textfields w/in the gui?
I've tried adding "this.paint(this.getGraphics());" within the infinite loop and it sort of works, but the updates to the gui are FAR SLOWER than the data that are streaming in from the server.
Thanks for any help!
The code looks something like this
Public class abc extends JFrame
Public abc()
     {initialize components}
instantiate all textfields & button
create various arrays
public void initialize components
     (set up gui using gridbaglayout
     add actionListener to button)
private actionperformed
(establish socket connection w/ server
     read data from server in an infinite loop
     parse data and use information to setText on the gui)
public static void main(blah blah)
     show abc();

have the reading loop in a different class which will have its own Thread running aside from the main program's thread. This way your application will do both at once :)

Similar Messages

  • ECATT: Command to execute a set of statements in an infinite loop

    Hi all,
    Is there any command in eCATT that executes a set of statements for an infinite number of times.
    I checked and could find commands like DO....ENDDO where the max count for DO is 9999.
    Let me know if there is any possibilty of executing this in eCATT
    Regards,
    Sushitha
    Edited by: Sushitha BV on Sep 24, 2010 12:04 PM

    Hi,
    Yes. it is possible to execute commands in Loop in ecatt.
    In the command editor, write your block of code within ABAP..ENDABAP
    ABAP.
    Do 10 Times.
    TCD(some recording)
    ENDDO.
    ENDABAP.
    Thanks
    Seema

  • Infinite loop when using the set language context API(This would be useful for f

    Hi below is the code when execute goes into the infinite loop
    Can any body throw light on this...
    Regards,
    Ranjit
    CREATE OR REPLACE procedure draw_custom_login_page
    site2pstoretoken in varchar2 default null
    ,p_error_code in varchar2 default null
    ,ssousername in varchar2 default null
    ,p_cancel_url in varchar2 default null
    ,p_submit_url in varchar2 default null
    AS
    var_bannergif                          varchar2(80);
    var_bannertitle                     varchar2(4000);
    var_bannerinfo                     varchar2(4000);
    var_linkname                          varchar2(4000);
    var_loginuser                     varchar2(4000);
    var_loginpwd                     varchar2(4000);
    var_loginbuttton                     varchar2(4000);
    var_listlangcaption                    varchar2(4000);
    var_optioneng                         varchar2(4000);
    var_optionspanish                    varchar2(4000);
    var_optionfrench                varchar2(4000);
    p_nls_language                varchar2(5);
    l_url                                   varchar2(4000);
    l_language                               varchar(2000);
    ex                                         exception;
    BEGIN
         -- for setting the browser language
              begin
                        --if (owa_cookie.get('NLS_LANGUAGE').vals.count = 0) then
                   -- if persistent NLS cookie is not found
                   -- get the preferred browser language from environment
                   --l_language := substr(wwctx_api.get_http_accept_language,0,2);
                                  --else
                                  --l_language:='us';
                        --end if;
                                  l_language := substr(wwctx_api.get_http_accept_language,0,2);
                                  l_url :='portal30_sso.draw_custom_login_page';
                                  if (owa_cookie.get('NLS_LANGUAGE').vals.count = 0) then
                                       -- set portal language and redirect instead of just redirect
                                       wwctx_app_language.set_language(p_http_language =>
                                                      l_language,p_nls_language => wwnls_api.http_to_nls(l_language),
                                       p_nls_territory => wwnls_api.territory_from_http_language(l_language),p_requested_url => l_url);
                             else
                                       owa_util.redirect_url(l_url);
                        end if;
         exception
         when others then
                   htp.p('Error Occurred');
         wwerr_api_error_ui.show_html;
              end;
         ----up to here
    --for retrieving the NLS Language Equivalents
         begin
         var_bannergif                := portal30.wwnls_api.get_string('CBS','banner_uitext','banner_gif',wwctx_api.get_nls_language);
         var_bannertitle                := portal30.wwnls_api.get_string('CBS','banner_uitext','banner_message',wwctx_api.get_nls_language);
         var_bannerinfo                    := portal30.wwnls_api.get_string('CBS','banner_uitext','banner_info',wwctx_api.get_nls_language);
         var_linkname                    := portal30.wwnls_api.get_string('CBS','banner_uilink','link_name',wwctx_api.get_nls_language);
         var_loginuser                    := portal30.wwnls_api.get_string('CBS','banner_uilogin','login_name',wwctx_api.get_nls_language);
         var_loginpwd                    := portal30.wwnls_api.get_string('CBS','banner_uilogin','login_password',wwctx_api.get_nls_language);
         var_loginbuttton                := portal30.wwnls_api.get_string('CBS','banner_uilogin','login_button',wwctx_api.get_nls_language);
         --for filling up the list box
         var_listlangcaption          := portal30.wwnls_api.get_string('CBS','banner_listlang','listlang_caption',wwctx_api.get_nls_language);
         var_optioneng                    := portal30.wwnls_api.get_string('CBS','banner_listlang','listlang_optioneng',wwctx_api.get_nls_language);
         var_optionspanish               := portal30.wwnls_api.get_string('CBS','banner_listlang','listlang_optionspan',wwctx_api.get_nls_language);
         var_optionfrench           := portal30.wwnls_api.get_string('CBS','banner_listlang','listlang_optionfrench',wwctx_api.get_nls_language);
         end;
    --Up to here
    htp.p('<HTML>');
    --htp.p('<FORM>');
    htp.p('<HEAD><TITLE>'||var_bannertitle||'</TITLE>');
    htp.p('<META content="text/html; charset=utf-8" http-equiv=Content-Type>');
    htp.p('<STYLE>.bodytext {COLOR: black; FONT-FAMILY: Verdana,Arial,Helvetica; FONT-SIZE: 11pt; fontFamily: Verdana,Arial,Helvetica}');
    htp.p('.header1 {');
         htp.p('FONT-FAMILY: Verdana,Arial,Helvetica; FONT-SIZE: 14pt; FONT-WEIGHT: bold; fontFamily: Verdana,Arial,Helvetica');
         htp.p('}');
         htp.p('.large {');
              htp.p('FONT-FAMILY: Verdana,Arial,Helvetica; FONT-SIZE: 18pt; FONT-WEIGHT: bold; fontFamily: Verdana,Arial,Helvetica}');
         htp.p('.small {');
              htp.p('FONT-FAMILY: Verdana,Arial,Helvetica; FONT-SIZE: 8pt; FONT-WEIGHT: normal; fontFamily: Verdana,Arial,Helvetica');
         htp.p('}');
         htp.p('</STYLE>');
         htp.p('<BODY leftMargin=0 topMargin=0 MarginWidth="0" MarginHeight="0"> ');
         htp.p('<TABLE background="/images/h_wave.gif" border=0 cellPadding=0 cellSpacing=0 width="100%">');
         htp.p('<TBODY>');
         htp.p('<TR>');
    htp.p('<TD height=36>  </TD></TR></TBODY></TABLE>');
         htp.p('<TABLE border=0 cellPadding=7 cellSpacing=0 width="100%">');
         htp.p('<TR>');
    htp.p('<TD height=36><IMG alt="" border=0 height=45 width=140 src="/images/'||var_bannergif||'"></TD>');
         htp.p('<TD height=36 align=right valign=top>');
         htp.p('<form name="cbs_language_select" action="PORTAL30_SSO.wwctx_app_language.set_language" method="POST">');
         htp.p('<input type="hidden" name="p_http_language" value="">');
    htp.p('<input type="hidden" name="p_nls_territory" value="">');
    htp.p('<input type="hidden" name="p_requested_url" value="portal30_sso.draw_custom_login_page">');
         htp.p('<select name=p_nls_language value="null" onChange="javascript:fn_cbs_lang_submit(p_nls_language)">');
         htp.p('<option selected>'||var_listlangcaption||'</option>');
         htp.p('<option value="us">'||var_optioneng||'</option>');
         htp.p('<option value="e">'||var_optionspanish||'</option>');
         htp.p('<option value="f">'||var_optionfrench||'</option>');
         htp.p('</select>');
         htp.p('</form>');
         htp.p('</TD> ');
         htp.p('</TR></TBODY></TABLE>');
         --htp.p('<DIV align=center>');
         htp.p('<TABLE border=0 cellPadding=5 cellSpacing=6 width=100%>');
         htp.p('<TBODY>');
         htp.p('<TR>');
         htp.p('<TD border=0 width=30%> </TD>');
         htp.p('<TD width=50%><span class=large>'||var_bannertitle||'</span>');
              htp.p('<P class=bodytext>'||var_bannerinfo||'<P>');
         --htp.p('Oracle''s financial applications to leverage the power of a single');
         --htp.p('integrated database with common data standards and core processes. This');
         --htp.p('tool empowers employees at their desktops, enabling them to requisition');
         --htp.p('goods and services, as well as pay bills and personal expenses online via');
         --htp.p('a Web browser.');
         htp.p(''||var_linkname);
         htp.p('');
         htp.p('<P align=center><A');
              htp.p('href="https://p2pweb1d.nj.ssmb.com:3043/pls/p2pdb30_portal30_sso"');
              htp.p('</TD>');
         --htp.p('<TD class=bodytext height=25>  </TD>');
         htp.p('<TD width=20% valign=top align=right >');
                        htp.p('<TABLE cellpadding=5 BGCOLOR="#F2F2F2"');
                        htp.p('<TR><TD align=right>');
                        htp.p('<p class=small><b>'||var_loginuser||'</b> <input class=small type=text size=15 name=user value="">');
                        htp.p('<P class=small><b>'||var_loginpwd||'</b> <input class=small type=password size=15 name=password value="">');
                        htp.p('</TD></TR>');
                        htp.p('<TR><TD align=right>');
                        htp.p('<input class=small type=button size=15 name=cmd_login value='||var_loginbuttton||'>');
                        htp.p('</TD></TR>');
                        htp.p('</TABLE>');
              htp.p('</TD>');
         htp.p('</TR></TBODY></TABLE>');
              --htp.p('</DIV>');
              htp.p('</BODY>');
              --htp.p('</FORM>');
              htp.p('</HTML>');
              htp.p('<SCRIPT language=JavaScript>');
                             htp.p('var l_http_language = new Array()');
                             htp.p('var l_nls_territory = new Array()');
                        htp.p('l_http_language[1] = "en"');
                        htp.p('l_nls_territory[1] = "AMERICA"');
                        htp.p('l_http_language[2] = "fr"');
                        htp.p('l_nls_territory[2] = "FRANCE"');
                        htp.p('l_http_language[3] = "de"');
                        htp.p('l_nls_territory[3] = "GERMANY"');
                        htp.p('l_http_language[4] = "ja"');
                        htp.p('l_nls_territory[4] = "JAPAN"');
                        htp.p('l_http_language[5] = "es"');
                        htp.p('l_nls_territory[5] = "SPANISH"');
                                                 htp.p('function fn_cbs_lang_submit(field){');
                                                                --htp.p('alert (document.cbs_language_select.p_http_language.value)');
                                                      htp.p('if ( field.selectedIndex != 0 )');
                                                      htp.p('{');
                                                      htp.p('document.cbs_language_select.p_http_language.value = l_http_language[field.selectedIndex]');
                                                                htp.p('document.cbs_language_select.p_nls_territory.value = l_nls_territory[field.selectedIndex]');
                                                      htp.p('document.cbs_language_select.submit();');
                                                      htp.p('}');
                                                                                              htp.p('}');
              htp.p('</SCRIPT>');
              exception when others then
              htp.p(l_language);
              htp.p(SQLCODE);
              htp.p(SQLERRM);
    END;

    Hi below is the code when execute goes into the infinite loop
    Can any body throw light on this...
    Regards,
    Ranjit
    CREATE OR REPLACE procedure draw_custom_login_page
    site2pstoretoken in varchar2 default null
    ,p_error_code in varchar2 default null
    ,ssousername in varchar2 default null
    ,p_cancel_url in varchar2 default null
    ,p_submit_url in varchar2 default null
    AS
    var_bannergif                          varchar2(80);
    var_bannertitle                     varchar2(4000);
    var_bannerinfo                     varchar2(4000);
    var_linkname                          varchar2(4000);
    var_loginuser                     varchar2(4000);
    var_loginpwd                     varchar2(4000);
    var_loginbuttton                     varchar2(4000);
    var_listlangcaption                    varchar2(4000);
    var_optioneng                         varchar2(4000);
    var_optionspanish                    varchar2(4000);
    var_optionfrench                varchar2(4000);
    p_nls_language                varchar2(5);
    l_url                                   varchar2(4000);
    l_language                               varchar(2000);
    ex                                         exception;
    BEGIN
         -- for setting the browser language
              begin
                        --if (owa_cookie.get('NLS_LANGUAGE').vals.count = 0) then
                   -- if persistent NLS cookie is not found
                   -- get the preferred browser language from environment
                   --l_language := substr(wwctx_api.get_http_accept_language,0,2);
                                  --else
                                  --l_language:='us';
                        --end if;
                                  l_language := substr(wwctx_api.get_http_accept_language,0,2);
                                  l_url :='portal30_sso.draw_custom_login_page';
                                  if (owa_cookie.get('NLS_LANGUAGE').vals.count = 0) then
                                       -- set portal language and redirect instead of just redirect
                                       wwctx_app_language.set_language(p_http_language =>
                                                      l_language,p_nls_language => wwnls_api.http_to_nls(l_language),
                                       p_nls_territory => wwnls_api.territory_from_http_language(l_language),p_requested_url => l_url);
                             else
                                       owa_util.redirect_url(l_url);
                        end if;
         exception
         when others then
                   htp.p('Error Occurred');
         wwerr_api_error_ui.show_html;
              end;
         ----up to here
    --for retrieving the NLS Language Equivalents
         begin
         var_bannergif                := portal30.wwnls_api.get_string('CBS','banner_uitext','banner_gif',wwctx_api.get_nls_language);
         var_bannertitle                := portal30.wwnls_api.get_string('CBS','banner_uitext','banner_message',wwctx_api.get_nls_language);
         var_bannerinfo                    := portal30.wwnls_api.get_string('CBS','banner_uitext','banner_info',wwctx_api.get_nls_language);
         var_linkname                    := portal30.wwnls_api.get_string('CBS','banner_uilink','link_name',wwctx_api.get_nls_language);
         var_loginuser                    := portal30.wwnls_api.get_string('CBS','banner_uilogin','login_name',wwctx_api.get_nls_language);
         var_loginpwd                    := portal30.wwnls_api.get_string('CBS','banner_uilogin','login_password',wwctx_api.get_nls_language);
         var_loginbuttton                := portal30.wwnls_api.get_string('CBS','banner_uilogin','login_button',wwctx_api.get_nls_language);
         --for filling up the list box
         var_listlangcaption          := portal30.wwnls_api.get_string('CBS','banner_listlang','listlang_caption',wwctx_api.get_nls_language);
         var_optioneng                    := portal30.wwnls_api.get_string('CBS','banner_listlang','listlang_optioneng',wwctx_api.get_nls_language);
         var_optionspanish               := portal30.wwnls_api.get_string('CBS','banner_listlang','listlang_optionspan',wwctx_api.get_nls_language);
         var_optionfrench           := portal30.wwnls_api.get_string('CBS','banner_listlang','listlang_optionfrench',wwctx_api.get_nls_language);
         end;
    --Up to here
    htp.p('<HTML>');
    --htp.p('<FORM>');
    htp.p('<HEAD><TITLE>'||var_bannertitle||'</TITLE>');
    htp.p('<META content="text/html; charset=utf-8" http-equiv=Content-Type>');
    htp.p('<STYLE>.bodytext {COLOR: black; FONT-FAMILY: Verdana,Arial,Helvetica; FONT-SIZE: 11pt; fontFamily: Verdana,Arial,Helvetica}');
    htp.p('.header1 {');
         htp.p('FONT-FAMILY: Verdana,Arial,Helvetica; FONT-SIZE: 14pt; FONT-WEIGHT: bold; fontFamily: Verdana,Arial,Helvetica');
         htp.p('}');
         htp.p('.large {');
              htp.p('FONT-FAMILY: Verdana,Arial,Helvetica; FONT-SIZE: 18pt; FONT-WEIGHT: bold; fontFamily: Verdana,Arial,Helvetica}');
         htp.p('.small {');
              htp.p('FONT-FAMILY: Verdana,Arial,Helvetica; FONT-SIZE: 8pt; FONT-WEIGHT: normal; fontFamily: Verdana,Arial,Helvetica');
         htp.p('}');
         htp.p('</STYLE>');
         htp.p('<BODY leftMargin=0 topMargin=0 MarginWidth="0" MarginHeight="0"> ');
         htp.p('<TABLE background="/images/h_wave.gif" border=0 cellPadding=0 cellSpacing=0 width="100%">');
         htp.p('<TBODY>');
         htp.p('<TR>');
    htp.p('<TD height=36>  </TD></TR></TBODY></TABLE>');
         htp.p('<TABLE border=0 cellPadding=7 cellSpacing=0 width="100%">');
         htp.p('<TR>');
    htp.p('<TD height=36><IMG alt="" border=0 height=45 width=140 src="/images/'||var_bannergif||'"></TD>');
         htp.p('<TD height=36 align=right valign=top>');
         htp.p('<form name="cbs_language_select" action="PORTAL30_SSO.wwctx_app_language.set_language" method="POST">');
         htp.p('<input type="hidden" name="p_http_language" value="">');
    htp.p('<input type="hidden" name="p_nls_territory" value="">');
    htp.p('<input type="hidden" name="p_requested_url" value="portal30_sso.draw_custom_login_page">');
         htp.p('<select name=p_nls_language value="null" onChange="javascript:fn_cbs_lang_submit(p_nls_language)">');
         htp.p('<option selected>'||var_listlangcaption||'</option>');
         htp.p('<option value="us">'||var_optioneng||'</option>');
         htp.p('<option value="e">'||var_optionspanish||'</option>');
         htp.p('<option value="f">'||var_optionfrench||'</option>');
         htp.p('</select>');
         htp.p('</form>');
         htp.p('</TD> ');
         htp.p('</TR></TBODY></TABLE>');
         --htp.p('<DIV align=center>');
         htp.p('<TABLE border=0 cellPadding=5 cellSpacing=6 width=100%>');
         htp.p('<TBODY>');
         htp.p('<TR>');
         htp.p('<TD border=0 width=30%> </TD>');
         htp.p('<TD width=50%><span class=large>'||var_bannertitle||'</span>');
              htp.p('<P class=bodytext>'||var_bannerinfo||'<P>');
         --htp.p('Oracle''s financial applications to leverage the power of a single');
         --htp.p('integrated database with common data standards and core processes. This');
         --htp.p('tool empowers employees at their desktops, enabling them to requisition');
         --htp.p('goods and services, as well as pay bills and personal expenses online via');
         --htp.p('a Web browser.');
         htp.p(''||var_linkname);
         htp.p('');
         htp.p('<P align=center><A');
              htp.p('href="https://p2pweb1d.nj.ssmb.com:3043/pls/p2pdb30_portal30_sso"');
              htp.p('</TD>');
         --htp.p('<TD class=bodytext height=25>  </TD>');
         htp.p('<TD width=20% valign=top align=right >');
                        htp.p('<TABLE cellpadding=5 BGCOLOR="#F2F2F2"');
                        htp.p('<TR><TD align=right>');
                        htp.p('<p class=small><b>'||var_loginuser||'</b> <input class=small type=text size=15 name=user value="">');
                        htp.p('<P class=small><b>'||var_loginpwd||'</b> <input class=small type=password size=15 name=password value="">');
                        htp.p('</TD></TR>');
                        htp.p('<TR><TD align=right>');
                        htp.p('<input class=small type=button size=15 name=cmd_login value='||var_loginbuttton||'>');
                        htp.p('</TD></TR>');
                        htp.p('</TABLE>');
              htp.p('</TD>');
         htp.p('</TR></TBODY></TABLE>');
              --htp.p('</DIV>');
              htp.p('</BODY>');
              --htp.p('</FORM>');
              htp.p('</HTML>');
              htp.p('<SCRIPT language=JavaScript>');
                             htp.p('var l_http_language = new Array()');
                             htp.p('var l_nls_territory = new Array()');
                        htp.p('l_http_language[1] = "en"');
                        htp.p('l_nls_territory[1] = "AMERICA"');
                        htp.p('l_http_language[2] = "fr"');
                        htp.p('l_nls_territory[2] = "FRANCE"');
                        htp.p('l_http_language[3] = "de"');
                        htp.p('l_nls_territory[3] = "GERMANY"');
                        htp.p('l_http_language[4] = "ja"');
                        htp.p('l_nls_territory[4] = "JAPAN"');
                        htp.p('l_http_language[5] = "es"');
                        htp.p('l_nls_territory[5] = "SPANISH"');
                                                 htp.p('function fn_cbs_lang_submit(field){');
                                                                --htp.p('alert (document.cbs_language_select.p_http_language.value)');
                                                      htp.p('if ( field.selectedIndex != 0 )');
                                                      htp.p('{');
                                                      htp.p('document.cbs_language_select.p_http_language.value = l_http_language[field.selectedIndex]');
                                                                htp.p('document.cbs_language_select.p_nls_territory.value = l_nls_territory[field.selectedIndex]');
                                                      htp.p('document.cbs_language_select.submit();');
                                                      htp.p('}');
                                                                                              htp.p('}');
              htp.p('</SCRIPT>');
              exception when others then
              htp.p(l_language);
              htp.p(SQLCODE);
              htp.p(SQLERRM);
    END;

  • Infinite loop in internet explorer after setting a doctype

    Hy,
    I have a problem with doctype, the internet explorer 6 - 8,  iframes and javascript. If I set the doctype to transitinal loose.dtd some of the Web Dynpro Applicatons which where included to my HTML page in form of iframes, produce javascript errors (looks like an infinite loop) so that every tested internet explorer crashes.
    Firefox has no problems and IE has no problems if:
    - I doesn't set any doctype (quirks mode)
    - or set a docype and open my iViews in a seperate Window
    I have no idea to solve this problem. I have to set a doctype. The cause of the problem lies in include iframes in the page and in the exclusive IE javascript file: sapUrMapi_ie6.js, where in the codelines 2643 - 2646 is an infinite loop because of some errors.
    What are the reasons for this javascript errors? How can I solve my problems?
    Thank you for every tip. Buy

    Hi Saeed.
    Thanks for your reply. As it turns out, the problem was how I was accessing the server, which was blocking display of some windows. I was using an IP address and once I used the name of the server instead, the access became a more approved level and I could access all the windows. Just FYI in case anyone else runs into this!
    Thanks!

  • [svn:fx-trunk] 10214: This fixes the problem that if two text components share the same textFlow there is an infinite loop involving updateDisplayList - damageHandler - invalidateDisplaylist - back to updateDisplayList.

    Revision: 10214
    Author:   [email protected]
    Date:     2009-09-13 07:33:58 -0700 (Sun, 13 Sep 2009)
    Log Message:
    This fixes the problem that if two text components share the same textFlow there is an infinite loop involving updateDisplayList -> damageHandler -> invalidateDisplaylist -> back to updateDisplayList.  The bug file was for TextArea which is RET but the same bug was in RichText as well.
    This example with a renderer exposed it because the typicalItem that is composed to figure out sizes and the actual first item in the list share the same textFlow.  It actually has nothing to do with useVirtualDisplay other than it was sharing a textFlow.
    It turns out that the TextFlowFactory dispatches damage events every time the textFlow is composed.  Unlike when the flowComposer is used, it always considers the flow damaged.  It was exacerbated by each of the two components having a damage handler for the same textFlow.
    The solution is to use the textFlow generation number.  In the damageHandler if the generation is the last known generation number, assume no changes, and return immediately from the damage handler.
    QE notes: There are 1 TextArea, 6 TextInput and 2 NumericStepper failuers, with or without my changes.  The common link seems to be DispatchKeyEvent.  Most were testing maxChar, displayAsPassword and restrict.  I tested these and they seem to be working correctly.
    Doc notes:
    Bugs: SDK-23002
    Reviewer: Gordon
    Tests run: checkintests, TextArea, TextInput and NumericStepper
    Is noteworthy for integration: no
    Ticket Links:
        http://bugs.adobe.com/jira/browse/SDK-23002
    Modified Paths:
        flex/sdk/trunk/frameworks/projects/spark/src/spark/components/RichEditableText.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/components/RichText.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/components/supportClasses/RichEditable TextContainerManager.as

    Revision: 10214
    Author:   [email protected]
    Date:     2009-09-13 07:33:58 -0700 (Sun, 13 Sep 2009)
    Log Message:
    This fixes the problem that if two text components share the same textFlow there is an infinite loop involving updateDisplayList -> damageHandler -> invalidateDisplaylist -> back to updateDisplayList.  The bug file was for TextArea which is RET but the same bug was in RichText as well.
    This example with a renderer exposed it because the typicalItem that is composed to figure out sizes and the actual first item in the list share the same textFlow.  It actually has nothing to do with useVirtualDisplay other than it was sharing a textFlow.
    It turns out that the TextFlowFactory dispatches damage events every time the textFlow is composed.  Unlike when the flowComposer is used, it always considers the flow damaged.  It was exacerbated by each of the two components having a damage handler for the same textFlow.
    The solution is to use the textFlow generation number.  In the damageHandler if the generation is the last known generation number, assume no changes, and return immediately from the damage handler.
    QE notes: There are 1 TextArea, 6 TextInput and 2 NumericStepper failuers, with or without my changes.  The common link seems to be DispatchKeyEvent.  Most were testing maxChar, displayAsPassword and restrict.  I tested these and they seem to be working correctly.
    Doc notes:
    Bugs: SDK-23002
    Reviewer: Gordon
    Tests run: checkintests, TextArea, TextInput and NumericStepper
    Is noteworthy for integration: no
    Ticket Links:
        http://bugs.adobe.com/jira/browse/SDK-23002
    Modified Paths:
        flex/sdk/trunk/frameworks/projects/spark/src/spark/components/RichEditableText.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/components/RichText.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/components/supportClasses/RichEditable TextContainerManager.as

  • Infinite Loop Gui Problem

    Hi all,
    Well basically I have 3 classes; one is called the loader which has the main function and all it does is call the second class which is the GUI class. This class buils up the GUI. The Third class however is a class which has an infinite loop inside until a button on the GUI is clicked. HOWEVER... due to the infinite loop, the GUI stays inactive until the loop ends which basically is like having a crashed GUI and thus the button can never be clicked!!
    What do you suggest? Shall the loader load the third class and the third class loads up the GUI? Or is that not practical?
    Thanks all

    Hi again,
    I still have a similar problem.
    basically whats happening is...
    From the GUI I launch a class with an infinite loop !!
    Part of the Loop is to await a connection and when connected, a new Class is again launched, it processes and closes itself, and returns back to the infinite loop !!
    I would like to know how I can Detach from the infinite loop to keep the GUI working...
    thanks all

  • Paint() method is in infinite loop when focus is set to JTextPane

    Hi All,
    I am creating one JScrollPane, JPanel and JTextPane. JPanel is added to JScrollPane and JTextPane is added to JPanel. If I override paint() method in JPanel, its in infinite loop. I don't know why it is behaving like this. Can anyone solve my problem. Since, I am doing so much drawings in paint() method, its getting to slow.
    Here is the code what I wrote.
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TestTextPane1 extends JFrame {
         JPanel panel;
         JScrollPane pane;
         public TestTextPane1() {
              panel = new JPanel(new BorderLayout()) {
                   public void paint(Graphics g) {
                        super.paint(g);
                        System.out.println("inside paint");
              JTextPane textPane = new JTextPane();
              panel.add(textPane);
              pane = new JScrollPane(panel);
              getContentPane().add(pane);
              setSize(300, 200);
              setVisible(true);
         public static void main(String [] args) {
              new TestTextPane1();
    Any help will be useful for me.
    Regards
    Kishore.

    What are you trying to do? You are adding the textPane to the panel and then overriding the paint() method. The textPane will never be painted if you do this.
    In Swing, you should override the paintComponent() method, not the paint() method. See the Swing tutorial on Painting:
    http://java.sun.com/docs/books/tutorial/uiswing/overview/draw.html
    Don't forget to read the "Working With Graphics" link at the bottom.

  • Infinite loop error after using Java Sun Tutorial for Learning Swing

    I have been attempting to create a GUI following Sun's learning swing by example (example two): http://java.sun.com/docs/books/tutorial/uiswing/learn/example2.html
    In particular, the following lines were used almost word-for-word to avoid a non-static method call problem:
    SwingApplication app = new SwingApplication();
    Component contents = app.createComponents();
    frame.getContentPane().add(contents, BorderLayout.CENTER);I believe that I am accidentally creating a new instance of the gui class repeatedly (since it shows new GUI's constantly and then crashes my computer), possibly because I am creating an instance in the main class, but creating another instance in the GUI itself. I am not sure how to avoid this, given that the tutorials I have seen do not deal with having a main class as well as the GUI. I have googled (a nice new verb) this problem and have been through the rest of the swing by example tutorials, although I am sure I am simply missing a website that details this problem. Any pointers on websites to study to avoid this problem would be appreciated.
    Thanks for your time-
    Danielle
    /** GUI for MicroMerger program
    * Created July/06 at IARC
    *@ author Danielle
    package micromerger;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.swing.JFileChooser;
    import java.lang.Object;
    public class MGui
         private static File inputFile1, inputFile2;
         private static File sfile1, sfile2;
         private static String file1Name, file2Name;
         private String currFile1, currFile2;
         private JButton enterFile1, enterFile2;
         private JLabel enterLabel1, enterLabel2;
         private static MGui app;
         public MGui()
              javax.swing.SwingUtilities.invokeLater(new Runnable()
                   public void run()
                        System.out.println("About to run create GUI method");
                        app = new MGui();
                        System.out.println("declared a new MGui....");
                        createAndShowGUI();
         //initialize look and feel of program
         private static void initLookAndFeel() {
            String lookAndFeel = null;
         lookAndFeel = UIManager.getSystemLookAndFeelClassName();
         try
              UIManager.setLookAndFeel(lookAndFeel);
         catch (ClassNotFoundException e) {
                    System.err.println("Couldn't find class for specified look and feel:"
                                       + lookAndFeel);
                    System.err.println("Did you include the L&F library in the class path?");
                    System.err.println("Using the default look and feel.");
                } catch (UnsupportedLookAndFeelException e) {
                    System.err.println("Can't use the specified look and feel ("
                                       + lookAndFeel
                                       + ") on this platform.");
                    System.err.println("Using the default look and feel.");
                } catch (Exception e) {
                    System.err.println("Couldn't get specified look and feel ("
                                       + lookAndFeel
                                       + "), for some reason.");
                    System.err.println("Using the default look and feel.");
                    e.printStackTrace();
         // Make Components--
         private Component createLeftComponents()
              // Make panel-- grid layout
         JPanel pane = new JPanel(new GridLayout(0,1));
            //Add label
            JLabel welcomeLabel = new JLabel("Welcome to MicroMerger.  Please Enter your files.");
            pane.add(welcomeLabel);
         //Add buttons to enter files:
         enterFile1 = new JButton("Please click to enter the first file.");
         enterFile1.addActionListener(new enterFile1Action());
         pane.add(enterFile1);
         enterLabel1 = new JLabel("");
         pane.add(enterLabel1);
         enterFile2 = new JButton("Please click to enter the second file.");
         enterFile2.addActionListener(new enterFile2Action());
         pane.add(enterFile2);
         enterLabel2 = new JLabel("");
         pane.add(enterLabel2);
         return pane;
         /** Make GUI:
         private static void createAndShowGUI()
         System.out.println("Creating a gui...");
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("MicroMerger");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         //Add stuff to the frame
         //MGui app = new MGui();
         Component leftContents = app.createLeftComponents();
         frame.getContentPane().add(leftContents, BorderLayout.WEST);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
    private class enterFile1Action implements ActionListener
         public void actionPerformed(ActionEvent evt)
              JFileChooser chooser = new JFileChooser();
              int rVal = chooser.showOpenDialog(enterFile1);
              if(rVal == JFileChooser.APPROVE_OPTION)
                   inputFile1 = chooser.getSelectedFile();
                   PrintWriter outputStream;
                   file1Name = inputFile1.getName();
                   enterLabel1.setText(file1Name);
    private class enterFile2Action implements ActionListener
         public void actionPerformed(ActionEvent evt)
              JFileChooser chooser = new JFileChooser();
              int rVal = chooser.showOpenDialog(enterFile1);
              if(rVal == JFileChooser.APPROVE_OPTION)
                   inputFile2 = chooser.getSelectedFile();
                   PrintWriter outputStream;
                   file2Name = inputFile2.getName();
                   enterLabel2.setText(file2Name);
    } // end classAnd now the main class:
    * Main.java
    * Created on June 13, 2006, 2:29 PM
    * @author Danielle
    package micromerger;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class Main
        /** Creates a new instance of Main */
        public Main()
         * @param args the command line arguments
        public static void main(String[] args)
            MGui mainScreen = new MGui();
            //mainScreen.setVisible(true);
            /**Starting to get file choices and moving them into GPR Handler:
             System.out.println("into main method");
         String file1Name = new String("");
             file1Name = MGui.get1Name();
         System.out.println("good so far- have MGui.get1Name()");
        }// end main(String[] args)
    }// end class Main

    um, yeah, you definitely have a recursion problem, that's going to create an infinite loop. you will eventually end up an out of memory error, if you don't first get the OS telling you you have too many windows. interestingly, because you are deferring execution, you won't get a stack overflow error, which you expect in an infinite recursion.
    lets examine why this is happening:
    in main, you call new MGui().
    new MGui() creates a runnable object which will be run on the event dispatch thread. That method ALSO calls new MGui(), which in turn ALSO creates a new object which will be run on the event dispatch thead. That obejct ALSO calls new MGui(), which ...
    well, hopefully you get the picture.
    you should never unconditionally call a method from within itself. that code that you have put in the constructor for MGui should REALLY be in the main method, and the first time you create the MGui in the main method as it currently exists is unnecessary.
    here's what you do: get rid of the MGui constructor altogether. since it is the implicit constructor anyway, if it doesn't do anything, you don't need to provide it.
    now, your main method should actually look like this:
    public static void main( String [] args ) {
      SwingUtilities.invokeLater( new Runnable() {
        public void run() {
          MGui app = new MGui();
          app.createAndShowGUI();
    }// end mainyou could also declare app and call the constructor before creating the Runnable, as many prefer, because you would have access to it from outside of the Runnable object. The catch there, though, is that app would need to be declared final.
    - Adam

  • JButton, flashcards and an infinite loop

    I'm trying a create a flashcard panel for Japanese kana. I have a class JCWidget that consists of the image of the specific symbol and its name.
    I could think of only two ways to create autoadvancing flashcards. Using Thread or Timer. May be there are more, and I would welcome the ideas.
    When the start button is pushed, an image and a name should change in a set ammount of seconds and so on, until the stop button is pressed But there is a problem - output is shown only after actionPerformed method is executed completely, resulting in infinite loop.
    Code using threads:
    public static JPanel addPanel2()
        jP2 = new JPanel(new GridLayout(2, 1));
        jcw = new JCWidget(arr, isKatakana);
        final JLabel letter = jcw.getLetter();
        final JLabel text = new JLabel(jcw.getLetterName());
        final JButton start = new JButton("Start flashcards");
        final JButton stop = new JButton("Stop flashcards");
        text.setHorizontalAlignment(JLabel.CENTER);
        stop.setEnabled(false);
        jP2.add(letter);
        jP2.add(start);
        jP2.add(text);
        jP2.add(stop);
        start.addActionListener(new ActionListener()
          public void actionPerformed(ActionEvent e)
            start.setEnabled(false);
            stop.setEnabled(true);
           while(stop.isEnabled())
              try {jcw.sleep(500);}
              catch (InterruptedException exept) {jcw.interrupt();}
              jcw = new JCWidget(arr, isKatakana);
              letter.setIcon(jcw.getLetter().getIcon());
              text.setText(jcw.getLetterName());
        stop.addActionListener(new ActionListener()
          public void actionPerformed(ActionEvent e)
            stop.setEnabled(false);
            start.setEnabled(true);
            jcw.notify();
        return jP2;
      }Code using timer:
    public static JPanel addPanel2()
        jP2 = new JPanel(new GridLayout(2, 1));
        jcw = new JCWidget(arr, isKatakana);
        final JLabel letter = jcw.getLetter();
        final JLabel text = new JLabel(jcw.getLetterName());
        final JButton start = new JButton("Start flashcards");
        final JButton stop = new JButton("Stop flashcards");
        text.setHorizontalAlignment(JLabel.CENTER);
        stop.setEnabled(false);
        jP2.add(letter);
        jP2.add(start);
        jP2.add(text);
        jP2.add(stop);
        final Timer timer = new Timer(1000, new ActionListener()
          public void actionPerformed(ActionEvent e)
           // while(stop.isEnabled())
              letter.setIcon(jcw.getLetter().getIcon());
              text.setText(jcw.getLetterName());
        start.addActionListener(new ActionListener()
          public void actionPerformed(ActionEvent e)
            start.setEnabled(false);
            stop.setEnabled(true);
            timer.start();
        stop.addActionListener(new ActionListener()
          public void actionPerformed(ActionEvent e)
            stop.setEnabled(false);
            start.setEnabled(true);
            timer.stop();
        return jP2;
      }When running for a single iteration, everything works perfectly, (although with timer can work only once - after pushing start button for the second time nothing would happen, with threads there is no problem in that.
    I tried to use for loop with limited number of iterations, but the output is changed only once - at the end of the loop. And with the while loop, program completely freezes up.
    Could someone, please, help?

        final Timer timer = new Timer(1000, 1000, new MyTimerActionListener());
        start.addActionListener(new ActionListener()
          public void actionPerformed(ActionEvent e)
            start.setEnabled(false);
            stop.setEnabled(true);
            timer.start();
        });To do the timer code better, you might want to construct a new timer each time the start button is pushed. Something like so:
        start.addActionListener(new ActionListener()
          public void actionPerformed(ActionEvent e)
            Timer timer = new Timer(1000, new MyTimerActionListener());
            start.setEnabled(false);
            stop.setEnabled(true);
            timer.start();
        });

  • PowerShell 3.0 stuck in infinite loop resolving members internally (is this a PS bug??)

    Sorry for long post... I have this scenario:
    - Issue is on PS3, PS2 works fine
    - I create a new object via "$myObj = New-Object PSObject"
    - I append a number of PSMembers to it via something similar to:
    "if (-not (Get-Member -InputObject $myObj -Name MyProperty))
     Add-Member -InputObject $myObj -MemberType ScriptProperty -Name MyProperty -Value { return MyFunction }
    I am seeing situations where what I believe is the call to "Get-Member" causes a huge number of invocations that appear to be calling the equivalent of the "MyFunction" in the above sample. I have debug statements in the MyFunction
    function and nested functions and can see they are called by what appears to be the PS framework itself. Even running a "Get-PSCallstack" call from one of these functions seems to also trigger the debug statements to be hit (midway through the callstack
    output??!) - bit confused by that but it's like PS is invoking the member in order to reflect it or something.
    I used Trace-Command and could see that the "MemberResolution" trace source is repeatedly/infinitely called with the output:
    MemberResolution Information: 0 :         Matching "*"
    MemberResolution Information: 0 :             Generating the total list of members
    MemberResolution Information: 0 :                 Type table members: 0.
    MemberResolution Information: 0 :                 Adapted members: 0.
    MemberResolution Information: 0 :             21 total matches.
    This appears to be in an infinite loop. Therefore I added "-ListenerOption Callstack" to the Trace-Command call and captured the following and more (notice the call to PSObject.ToStringEmptyBaseObject()):
    at System.Management.Automation.PSObject.AdapterGetMembersDelegate[T](PSObject msjObj)
       at System.Management.Automation.PSMemberInfoIntegratingCollection`1.GetIntegratedMembers(MshMemberMatchOptions matchOptions)
       at System.Management.Automation.PSMemberInfoIntegratingCollection`1.Match(String name, PSMemberTypes memberTypes, MshMemberMatchOptions matchOptions)
       at System.Management.Automation.PSObject.ToStringEmptyBaseObject(ExecutionContext context, PSObject mshObj, String separator, String format, IFormatProvider formatProvider)
       at System.Management.Automation.PSObject.ToString(ExecutionContext context, Object obj, String separator, String format, IFormatProvider formatProvider, Boolean recurse, Boolean unravelEnumeratorOnRecurse)
       at System.Management.Automation.PSObject.ToString()
       at System.String.Join(String separator, Object[] values)
       at System.Management.Automation.ParameterBinderBase.BindParameter(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, ParameterBindingFlags flags)
    I then disassembled the relevant code in Reflector and could see that the ToString() method of PSObject has a check for "if obj.immediateBaseObjectIsEmpty" then to call the ToStringEmptyBaseObject() function. I could also see that the immediateBaseObjectIsEmpty
    field is set in the CommonInitialization internal method if "obj is PSCustomObject" (which is the actual object type you get when you New-Object PSObject).
    I then updated my code to create "$myObj = New-Object Object" (i.e. System.Object instead) and the issue goes away.
    Can anyone explain what I may have done wrong here or is this looking like a bug in PowerShell?
    Cheers!

    Hi Matt,
    I'm not sure if we are on the same page? Getting the list of (i.e. metadata of) the members shouldn't invoke the member.  I have used this technique in many places and it's never been an issue whereby you "wrap" a utility function with
    a ScriptProperty or ScriptMethod to provide OO semantics on a PS object. The member isn't invoked by Get-Member, only when it's called explicitly.
    Here's a small example:
    function TestFunction
     Write-Host "TestFunction called"
     return "TestFunction return value"
    $myObj = New-Object PSObject
    Add-Member -InputObject $myObj -MemberType ScriptProperty -Name TestScriptProperty -Value `
     Write-Host "TestScriptProperty called"
     return TestFunction
    Write-Host "Getting members"
    Get-Member -InputObject $myObj -Name TestScriptProperty | Select *
    Write-Host "Invoking property"
    $myObj.TestScriptProperty
    Here's the output (Get-Member output a bit mangled due to the text wrapping):
    Getting members
    TypeName                                   Name                                                                      
    MemberType Definition                               
    System.Management.Automation.PSCustomOb... TestScriptProperty                                                    
    ScriptProperty System.Object TestScriptProperty {get=...
    Invoking property
    TestScriptProperty called
    TestFunction called
    TestFunction return value
    Yup I see your point, but when you run your original code with this example object you can see there is no loop. There must either be a loop in the function or in the body of the script itself. This is very tough to troubleshoot without seeing the code you
    are actually running.
    You said you are adding several members to the custom object. Is this done in a loop?

  • Start/Stop Buttons and infinite loop exit

    I am trying to make a GUI with a Start/Stop and an Exit button. Initially the button will have the label "Start". When i push it, its label should become "Stop" and an infinite loop function will begin. I want the loop to run until i press the Stop or Exit button.
    The problem is that when the loop starts i can't press neither of the buttons. The "Start" button changes its label into "Stop" only if i make the loop finite and it ends.
    Here is the source:
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class StartStopButtons extends JFrame{
        Component visualComponent = null;
        JPanel panel = null;
        JLabel statusBar = null;
         public StartStopButtons() {
              setSize(160, 70);
              getContentPane().setLayout(new BorderLayout());
            panel = new JPanel();
            panel.setLayout(new BorderLayout());
            getContentPane().add(panel, BorderLayout.CENTER);
            final JPanel panel_1 = new JPanel();
            panel.add(panel_1, BorderLayout.CENTER);
            final JButton startButton = new JButton();
            startButton.addActionListener(new ActionListener() {
                 public void actionPerformed(final ActionEvent e) {
                    String action = e.getActionCommand();
                    if (action.equals("Start")) {
                         System.out.println("Start Loop");
                         startButton.setText("Stop");
                         myLoop ();
                    if (action.equals("Stop")) {
                         System.out.println("Stop Loop");
                         System.exit(0);
            startButton.setText("Start");
            panel_1.add(startButton);
            final JButton exitButton = new JButton();
            exitButton.addActionListener(new ActionListener() {
                 public void actionPerformed(final ActionEvent e) {
                    String action = e.getActionCommand();
                    if (action.equals("Exit")) {
                        System.exit(0);
            panel_1.add(exitButton);
            exitButton.setText("Exit");
         public void myLoop() {
              for (int i = 0; ; i++)
                   System.out.println(i);
         public static void main(String[] args) {
              StartStopButtons ssB = new StartStopButtons();
              ssB.setVisible(true);
    }

    I works just fine. Here is the source and thanks for the help.
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.UIManager;
    public class StartStopButtons extends JFrame implements ActionListener, Runnable{
        Component visualComponent = null;
        JPanel panel = null;
        JLabel statusBar = null;
        Thread thread;
        JButton startButton;
         public StartStopButtons() {
            try {
                UIManager.setLookAndFeel(
                    UIManager.getSystemLookAndFeelClassName());
            } catch(Exception e) {}
              setSize(160, 70);
              getContentPane().setLayout(new BorderLayout());
            panel = new JPanel();
            panel.setLayout(new BorderLayout());
            getContentPane().add(panel, BorderLayout.CENTER);
            final JPanel panel_1 = new JPanel();
            panel.add(panel_1, BorderLayout.CENTER);
            startButton = new JButton();
            startButton.addActionListener(this);
            startButton.setText("Start");
            panel_1.add(startButton);
            final JButton exitButton = new JButton();
            exitButton.addActionListener(new ActionListener() {
                 public void actionPerformed(final ActionEvent e) {
                    String action = e.getActionCommand();
                    if (action.equals("Exit")) {
                        System.exit(0);
            panel_1.add(exitButton);
            exitButton.setText("Exit");
         public void actionPerformed(ActionEvent e) {
              String action = e.getActionCommand();
              if (action.equals("Start")) {
                   startButton.setText("Stop");
                   thread = new Thread( this );
                   thread.start();
              if (action.equals("Stop")) {
                System.exit(0);
         public void run() {
              myLoop();
         public void myLoop() {
              for (int i = 0; ; i++)
                   System.out.println(i);
         public static void main(String[] args) {
              StartStopButtons ssB = new StartStopButtons();
              ssB.setVisible(true);
    }

  • Interupt an infinite loop

    Hi all
    I was wondering if anyone could offer some help on a problem of mine
    I have a GUI with a button (labeled start), when its clicked it starts an infinite loop that is stopped by the same button (obviously after the first click the text changes to stop) . The problem i`m trying to solve is that once the loop is started the GUI`s action listener wont be able to listen for the second click(cause the listener is still waiting for the loop to stop)
    Can anyone think of a work around for this problem
    oh and the loop cannot be interrupted other than the 'click' as it needs to constantly change the values on screen
    There`s probably a simple solution that Ive missed but i cant think of it - just going in circles now
    Any help and suggestions welcome
    Thanks
    Matt

    yeah it could be a while loop but the program will continue with the loop and not get the second click - so it cant change the variable e.g.
    boolean stop = false;
    onClick (inline listener){
        if(firstClick){     
             startLoop();      // <<<program will freeze here until function finishes - but will never finish (making it impossible to receive the next click;
         }else{
              stop = true;  
    void startLoop(){   
         while(!stop){  
             //ect
    }hope that helps clear it up
    thanks for the prompt reply

  • Program enters infinite loop.

    this is the first program i'm writing with sockets and is also a step towards making a chat application. my problem is that the program enters infinite loop.
    package server;
    import java.net.*;
    import java.io.*;
    class Server
        public static void main(String[] args) throws Exception
            ServerSocket ss = new ServerSocket(9090);
            Socket soc = ss.accept();
            BufferedReader in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
            String str = in.readLine();
            while(str!="")
                System.out.println(str);
                str = in.readLine();
            soc.close();
            ss.close();
    }this was the server - a seperate application. below is a part of the client - a seperate application
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            try
                InetAddress ip = InetAddress.getByName("127.0.0.1");
                Socket soc = new Socket(ip,9090);
                PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(soc.getOutputStream())),true);
                str_out = jTextArea2.getText();
                while(str_out!="")
                    out.println(str_out);
                    str_out = jTextArea2.getText();
                soc.close();
            catch(Exception e)
                System.out.println("Error sending message");
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            str_out = "";
            jTextArea2.setText(str_out);
        }  when i press button send (jButton1) the text from the text area jTextArea2 is supposed to go to the server and then the server should display it in its out put screen. i tried sending hello and the server went on printing hello continously.
    pleas help.

    String str = in.readLine();
    while(str!="")
    System.out.println(str);
    str = in.readLine();
    }You need to test for (str != null) above too, or instead of str != "".

  • Can anyone figure out why this runs into an infinite loop?

    Hi,
    I have the following class, and if i run it, I encounter an infinite loop. I have pinpointed the problem and it is because of the lines:
    try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch (Exception exp) {
                   System.err.println("Failed");
                exp.printStackTrace();
            }Here is the class. Any and all help is greatly appreciated. Thanks!
    package org.aemf.clinical.tol.gui.printing;
    import org.aemf.clinical.tol.model.TOLBion;
    import org.aemf.clinical.tol.model.Range;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.*;
    import java.awt.print.*;
    import java.awt.*;
    import java.util.Iterator;
    import java.util.ArrayList;
    * Created by IntelliJ IDEA.
    * User: arashn
    * Date: Feb 9, 2005
    * Time: 1:26:38 PM
    public class printTableTest implements Printable, Pageable {
         private PageFormat pf;
         private String[] headers = { "Heading 1", "Heading 2", "Heading 3"};
         private java.util.List bions = null;
         private ArrayList<Object[][]> data = new ArrayList<Object[][]>();
         public printTableTest(PageFormat format) {
              this.pf = format;
         public int getNumberOfPages() {
            return 1;
        public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException {
            return pf;
         public void setBions(java.util.List b) {
              bions = b;
              for(int x=0; x < 3; x++) {
                   //TOLBion bion = (TOLBion) bions.get(x);
                   int ndx = 0;
                   //Object[][] tempData = new Object[bion.getNumRanges()][3];
                   Object[][] tempData = new Object[2][3];
              //     for (Iterator itr = bion.getRanges(); ndx < 2 && itr.hasNext(); ) {
                   for (; ndx < 2 ; ) {
                   // Range range = (Range)itr.next();
                        //tempData[ndx] = new Object[] { new Integer(range.getFrequency()), range.getLowerBound(), range.getUpperBound() };
                        tempData[ndx] = new Object[] { "col 1: " + x, "col 2: " + x, "col 3: " + x };
                        ndx++;
                   data.add(tempData);
        public Printable getPrintable(int pageIndex) throws IndexOutOfBoundsException {
            return this;
         public int print(Graphics g, PageFormat format, int pageIndex) throws PrinterException {
              if(pageIndex > 1) {
                   return Printable.NO_SUCH_PAGE;
                                                                              System.err.println("Page: " + pageIndex);
              JFrame frame = null;
              JTable tableView = null;
              Graphics2D g2 = (Graphics2D) g;
              //Object[][] data = new Object[3][3];
              g2.setColor(Color.black);
              g2.translate(format.getImageableX() + 72, format.getImageableY() + 72);
              for(int x=0; x < data.size(); x++) {
                   tableView = new JTable(new PrintTableModel(headers, data.get(x)));
                   frame = new JFrame();
                   JScrollPane scrollpane = new JScrollPane(tableView);
                   scrollpane.setPreferredSize(new Dimension(300, 80));
                   frame.getContentPane().setLayout(new BorderLayout());
                   frame.getContentPane().add(BorderLayout.CENTER,scrollpane);
                   frame.pack();
                   tableView.paint(g2);
                   g2.translate(0, - tableView.getTableHeader().getHeight());
                   tableView.getTableHeader().paint(g2);
                   g2.translate(0, format.getImageableHeight()/3);
              return Printable.PAGE_EXISTS;
         public static void main(String args[]) {
              PrinterJob printerJob = PrinterJob.getPrinterJob();
              try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch (Exception exp) {
                   System.err.println("Failed");
                exp.printStackTrace();
             int INCH = 72;
              double LETTER_WIDTH = 8.5 * INCH;
              double LETTER_HEIGHT = 11 * INCH;
            Paper paper = new Paper();
              int margin = INCH/6; // << set your margins here
              double pageWidth = LETTER_WIDTH - 2 * margin;
              double pageHeigth = LETTER_HEIGHT - 2 * margin;
              paper.setImageableArea(margin, margin, pageWidth, pageHeigth) ;
              PageFormat format = printerJob.defaultPage();
              format.setPaper(paper);
            printTableTest pp = new printTableTest(format);
            pp.setBions(new ArrayList());
              printerJob.setPageable(pp);
              boolean doPrint = printerJob.printDialog();
              if (doPrint) {
                   try {
                        printerJob.print();
                   } catch (PrinterException exception) {
                        System.err.println("Printing error: " + exception);
             System.exit(0);
         private class PrintTableModel extends AbstractTableModel {
              private Object[][] data = null;
              private String[] headers = null;
              public PrintTableModel(String[] headers, Object[][] data) {
                   this.headers = headers;
                   this.data = data;
              public int getColumnCount() { return headers.length; }
              public int getRowCount() { return data.length; }
              public Object getValueAt(int row, int col) { return data[row][col]; }
              public String getColumnName(int column) { return headers[column]; }
              public Class getColumnClass(int col) { return getValueAt(0,col).getClass(); }
              public boolean isCellEditable(int row, int col) { return false; }
              public void setValueAt(Object aValue, int row, int column) { data[row][column] = aValue; }
    }

    I have managed to create an even simpler version which tries to print the same header 3 times. Again, if you remove the setLookAndFeel line, everything works out great.
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.print.*;
    import java.awt.*;
    * Created by IntelliJ IDEA.
    * User: arashn
    * Date: Feb 9, 2005
    * Time: 1:26:38 PM
    public class printTableTest implements Printable, Pageable {
         private PageFormat pf;
         public printTableTest(PageFormat format) {
              this.pf = format;
         public int getNumberOfPages() {
            return 1;
        public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException {
            return pf;
        public Printable getPrintable(int pageIndex) throws IndexOutOfBoundsException {
            return this;
         public int print(Graphics g, PageFormat format, int pageIndex) throws PrinterException {
              if(pageIndex > 1) {
                   return Printable.NO_SUCH_PAGE;
              System.err.println("Printing Page: " + pageIndex);
              Graphics2D g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              g2.translate(format.getImageableX() + 72, format.getImageableY() + 72);
              DefaultTableColumnModel dtcm = new DefaultTableColumnModel();
              TableColumn tc = new TableColumn();
              tc.setHeaderValue("Heading 1");
              dtcm.addColumn(tc);
              tc.setHeaderValue("Heading 2");
              dtcm.addColumn(tc);
              tc.setHeaderValue("Heading 2");
              dtcm.addColumn(tc);
              JTableHeader tableHeader = new JTableHeader(dtcm);
              JScrollPane scrollpane2 = new JScrollPane(tableHeader);
              scrollpane2.setPreferredSize(new Dimension(300, 80));
              JFrame frame2 = new JFrame();
              frame2.getContentPane().add(BorderLayout.NORTH,scrollpane2);
              frame2.pack();
              for(int x=0; x < 3; x++) {                   
                   tableHeader.paint(g2);
                   g2.translate(0, format.getImageableHeight()/3);
              return Printable.PAGE_EXISTS;
         public static void main(String args[]) {
              PrinterJob printerJob = PrinterJob.getPrinterJob();
              try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch (Exception exp) {
                   System.err.println("Failed");
                exp.printStackTrace();
             int INCH = 72;
              double LETTER_WIDTH = 8.5 * INCH;
              double LETTER_HEIGHT = 11 * INCH;
            Paper paper = new Paper();
              int margin = INCH/6; // << set your margins here
              double pageWidth = LETTER_WIDTH - 2 * margin;
              double pageHeigth = LETTER_HEIGHT - 2 * margin;
              paper.setImageableArea(margin, margin, pageWidth, pageHeigth) ;
              PageFormat format = printerJob.defaultPage();
              format.setPaper(paper);
            printTableTest pp = new printTableTest(format);
              printerJob.setPageable(pp);
              boolean doPrint = printerJob.printDialog();
              if (doPrint) {
                   try {
                        printerJob.print();
                   } catch (PrinterException exception) {
                        System.err.println("Printing error: " + exception);
             System.exit(0);
    }

  • SQL stored procedure Staging.GroomDwStagingData stuck in infinite loop, consuming excessive CPU

    Hello
    I'm hoping that someone here might be able to help or point me in the right direction. Apologies for the long post.
    Just to set the scene, I am a SQL Server DBA and have very limited experience with System Centre so please go easy on me.
    At the company I am currently working they are complaining about very poor performance when running reports (any).
    Quick look at the database server and CPU utilisation being a constant 90-95%, meant that you dont have to be Sherlock Holmes to realise there is a problem. The instance consuming the majority of the CPU is the instance hosting the datawarehouse and in particular
    a stored procedure in the DWStagingAndConfig database called Staging.GroomDwStagingData.
    This stored procedure executes continually for 2 hours performing 500,000,000 reads per execution before "timing out". It is then executed again for another 2 hours etc etc.
    After a bit of diagnosis it seems that the issue is either a bug or that there is something wrong with our data in that a stored procedure is stuck in an infinite loop
    System Center 2012 SP1 CU2 (5.0.7804.1300)
    Diagnosis details
    SQL connection details
    program name = SC DAL--GroomingWriteModule
    set quoted_identifier on
    set arithabort off
    set numeric_roundabort off
    set ansi_warnings on
    set ansi_padding on
    set ansi_nulls on
    set concat_null_yields_null on
    set cursor_close_on_commit off
    set implicit_transactions off
    set language us_english
    set dateformat mdy
    set datefirst 7
    set transaction isolation level read committed
    Store procedures executed
    1. dbo.p_GetDwStagingGroomingConfig (executes immediately)
    2. Staging.GroomDwStagingData (this is the procedure that executes in 2 hours before being cancelled)
    The 1st stored procedure seems to return a table with the "xml" / required parameters to execute Staging.GroomDwStagingData
    Sample xml below (cut right down)
    <Config>
    <Target>
    <ModuleName>TransformActivityDim</ModuleName>
    <WarehouseEntityName>ActivityDim</WarehouseEntityName>
    <RequiredWarehouseEntityName>MTV_System$WorkItem$Activity</RequiredWarehouseEntityName>
    <Watermark>2015-01-30T08:59:14.397</Watermark>
    </Target>
    <Target>
    <ModuleName>TransformActivityDim</ModuleName>
    <WarehouseEntityName>ActivityDim</WarehouseEntityName>
    <RequiredWarehouseEntityName>MTV_System$WorkItem$Activity</RequiredWarehouseEntityName>
    <ManagedTypeViewName>MTV_Microsoft$SystemCenter$Orchestrator$RunbookAutomationActivity</ManagedTypeViewName>
    <Watermark>2015-01-30T08:59:14.397</Watermark>
    </Target>
    </Config>
    If you look carefully you will see that the 1st <target> is missing the ManagedTypeViewName, which when "shredded" by the Staging.GroomDwStagingData returns the following result set
    Example
    DECLARE @Config xml
    DECLARE @GroomingCriteria NVARCHAR(MAX)
    SET @GroomingCriteria = '<Config><Target><ModuleName>TransformActivityDim</ModuleName><WarehouseEntityName>ActivityDim</WarehouseEntityName><RequiredWarehouseEntityName>MTV_System$WorkItem$Activity</RequiredWarehouseEntityName><Watermark>2015-01-30T08:59:14.397</Watermark></Target><Target><ModuleName>TransformActivityDim</ModuleName><WarehouseEntityName>ActivityDim</WarehouseEntityName><RequiredWarehouseEntityName>MTV_System$WorkItem$Activity</RequiredWarehouseEntityName><ManagedTypeViewName>MTV_Microsoft$SystemCenter$Orchestrator$RunbookAutomationActivity</ManagedTypeViewName><Watermark>2015-01-30T08:59:14.397</Watermark></Target></Config>'
    SET @Config = CONVERT(xml, @GroomingCriteria)
    SELECT
    ModuleName = p.value(N'child::ModuleName[1]', N'nvarchar(255)')
    ,WarehouseEntityName = p.value(N'child::WarehouseEntityName[1]', N'nvarchar(255)')
    ,RequiredWarehouseEntityName =p.value(N'child::RequiredWarehouseEntityName[1]', N'nvarchar(255)')
    ,ManagedTypeViewName = p.value(N'child::ManagedTypeViewName[1]', N'nvarchar(255)')
    ,Watermark = p.value(N'child::Watermark[1]', N'datetime')
    FROM @Config.nodes(N'/Config/*') Elem(p)
    /* RESULTS - NOTE THE NULL VALUE FOR ManagedTypeViewName
    ModuleName WarehouseEntityName RequiredWarehouseEntityName ManagedTypeViewName Watermark
    TransformActivityDim ActivityDim MTV_System$WorkItem$Activity NULL 2015-01-30 08:59:14.397
    TransformActivityDim ActivityDim MTV_System$WorkItem$Activity MTV_Microsoft$SystemCenter$Orchestrator$RunbookAutomationActivity 2015-01-30 08:59:14.397
    When the procedure enters the loop to build its dynamic SQL to delete relevant rows from the inbound schema tables it concatenates various options / variables into an executable string. However when adding a NULL value to a string the entire string becomes
    NULL which then gets executed.
    Whilst executing "EXEC(NULL)" would cause SQL to throw an error and be caught, executing the following doesnt
    DECLARE @null_string VARCHAR(100)
    SET @null_string = 'hello world ' + NULL
    EXEC(@null_string)
    SELECT @null_string
    So as it hasnt caused an error the next part of the procedure is to move to the next record and this is why its caught in an infinite loop
    DELETE @items WHERE ManagedTypeViewName = @View
    The value for the variable @View is the ManagedTypeViewName which is NULL, as ANSI_NULLS are set to ON in the connection and not overridded in the procedure then the above statement wont delete anything as it needs to handle NULL values differently (IS NULL),
    so we are now stuck in an infinite loop executing NULL for 2 hours until cancelled.
    I amended the stored procedure and added the following line before the loop statement which had the desired effect and "fixed" the performance issue for the time being
    DELETE @items WHERE ManagedTypeViewName IS NULL
    I also noticed that the following line in dbo.p_GetDwStagingGroomingConfig is commented out (no idea why as no notes in the procedure)
    --AND COALESCE(i.ManagedTypeViewName, j.RelationshipTypeViewName) IS NOT NULL
    There are obviously other ways to mitigate the dynamic SQL string being NULL, there's more than one way to skin a cat and thats not why I am asking this question, but what I am concerned about is that is there a reason that the xml / @GroomingCriteria is incomplete
    and / or that the procedures dont handle potential NULL values.
    I cant find any documentation, KBs, forum posts of anyone else having this issue which somewhat surprises me.
    Would be grateful of any help / advice that anyone can provide or if someone can look at their 2 stored procedures on a later version to see if it has already been fixed. Or is it simply that we have orphaned data, this is the bit that concerns most as I dont
    really want to be deleting / updating data when I have no idea what the knock on effect might be
    Many many thanks
    Andy

    First thing I would do is upgrade to 2012 R2 UR5. If you are running non-US dates you need the UR5 hotfix also.
    Rob Ford scsmnz.net
    Cireson www.cireson.com
    For a free SCSM 2012 Notify Analyst app click
    here

Maybe you are looking for