Force to java to listen events

My problem is this: when When i�m executing certain loop in my application, the JVM doesn�t listen the events that occurs (that is, the actionPerformed method isn�t invocated when i push a JButton). When the loop finished, the problem dissapear. �Anybody knows some call that force to java to listen events?. I�ve tried to implement this loop in a thread but the problem doesn�t dissapear.
Thanks.

if the loop is started from a gui event handler, take a look at SwingUtilities.invokeLater() method
Nic

Similar Messages

  • Listener event

    I am trying to create a small game got most of the functionality, apart from one aspect how would you code an Listener event that would take into account that if any two pawns on a chessboard were on the same line in any direction then that row would become highlighted and the user could not place any more pawns on that row?
    I know a wee bit about �if� and �else� statements but I have no idea how you would create code that would carry out the above function.
    Any help would be great
    Tom
    // <applet code="ChessBored.class" width="500" height="500"></applet>
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class ChessBored  extends JApplet
      public void init()
         JFrame f = new JFrame("Chess Board");
         ChessBoard board = new ChessBoard();
         f.getContentPane().add(board);
         f.setSize(board.WIDTH, board.HEIGHT);
         f.setVisible(true);
       } // end init
      public class ChessBoard extends JPanel implements MouseListener
        private Color[] squareColor = new Color[2];
        private final int NUMSQUARES = 8, WIDTH = 400, HEIGHT = 400;
        private int squareSize;
        private int boardSize;
    /* The constructor sets only some of the instance variables.
       The rest are set when the screen is painted.
       public ChessBoard()
          squareColor[0] = Color.black;
          squareColor[1] = Color.white;
          addMouseListener(this);
          setSize(WIDTH, HEIGHT);
    /* The paintComponent method is called every time the display
       needs to be repainted. Examples: When the window is
       first displayed, when the window is moved, resized,
       maximized, etc.
       Draws an 8x8 grid of alternately colored squares.
       Make the grid as large as it can be to fit in the
       current size of the drawing pane (which is the content pane
       for the JFrame).
        public void paintComponent (Graphics g)
          super.paintComponent(g);  // Make sure background is cleared
          int paneHeight = this.getHeight();
          int paneWidth  = this.getWidth();
          if (paneHeight < paneWidth)
            squareSize = paneHeight / NUMSQUARES;
          else
            squareSize = paneWidth / NUMSQUARES;
          boardSize = squareSize * NUMSQUARES;
          for (int row=0; row<NUMSQUARES; row++)
             for (int col=0; col!=NUMSQUARES; col++)
            { g.setColor(squareColor[(row+col)%2]);
              g.fillRect(col*squareSize,   // x
                         row*squareSize,   // y
                         squareSize,       // width
                         squareSize);      // height
        } // end paintComponent
    /** The mouseClicked method responds to any mouse clicks.
        public void mousePressed(MouseEvent e)
    // Quit if the mouse press falls outside the board
          Point p = e.getPoint();
          int x = (int) p.getX();
          int y = (int) p.getY();
          if((x>boardSize) || (y>boardSize))
            return;
    // Determine which square (i.e. row, col) was selected
          int row = y / squareSize;
          int col = x / squareSize;
          if (row <= 8)
            drawPawn(row, col, Color.blue);
        //else
          //if (row >= (NUMSQUARES-2))
            //drawPawn(row, col, Color.black);
          //else
           // drawMessage(row, "Checkmate!");
    /* These four methods are not used, but must be
       implemented because they are required by the
       MouseListener interface.
        public void mouseEntered(MouseEvent e)  {}
        public void mouseExited(MouseEvent e)   {}
        public void mouseClicked(MouseEvent e)  {}
        public void mouseReleased(MouseEvent e) {}
    /** The drawPawn method draws a pawn shape on the
        specified square in the chess board.
        public void drawPawn(int row, int col, Color c)
          Graphics g = this.getGraphics();
          g.setColor(c);
    // Calculate position of upper left corner of square
          int x = col*squareSize;
          int y = row*squareSize;
    /* Draw circle for "head" of the pawn. Dimensions are
       for the oval's "bounding box".
          g.fillOval(x+(2*squareSize/5), // x
                     y+(squareSize/5),   // y
                     squareSize/5,       // width
                     squareSize/5);      // height
    // Draw a polygon for the "body" of the pawn.
          Polygon body = new Polygon();
          body.addPoint(x+(2*squareSize/5),
                        y+(2*squareSize/5));
          body.addPoint(x+(3*squareSize/5),
                        y+(2*squareSize/5));
          body.addPoint(x+(4*squareSize/5),
                        y+(4*squareSize/5));
          body.addPoint(x+(squareSize/5),
                        y+(4*squareSize/5));
          g.fillPolygon(body);
        } // drawPawn
    /** The drawMessage method draws the given string in
        the given row of the chess board, centered
        horizontally.
        public void drawMessage(int row, String s)
    //Set a new font and color
          Font bigFont = new Font("Times New Roman", Font.BOLD, 36);
          Graphics g = this.getGraphics();
          g.setFont(bigFont);
          g.setColor(new Color(0.8F, 0.8F, 1.0F));
    //Determine the position of the string
          FontMetrics m = g.getFontMetrics();
          int x = (boardSize - m.stringWidth(s)) / 2;
          if (x < 0)
            x = 0;
          int y = ((row+1)*squareSize) - m.getDescent();
          if (y<0)
            y = m.getLeading() + m.getAscent();
          g.drawString(s, x, y);
        } // drawMessage
      } // end ChessBoard
    } // end ChessBored

    One thing that sticks out is your listener method isn't quite to spec, according to the f:ajax spec they're supposed to match the following signature:
    javax.el.MethodExpression
    (signature must match public void processAjaxBehavior(javax.faces.event.AjaxBehaviorEvent event) throws javax.faces.event.AbortProcessingException)
    Try dropping the boolean return value & adding the throws. I'm running Apache's MyFaces and it's perfectly fine with your method signature, but maybe your JSF implementation isn't.
    Also, you running with javax.faces.PROJECT_STAGE set to Development? Maybe some useful server-side error you're not seeing. You probably should also create your own ExceptionHandler to dump stack traces to the console/logs if you haven't done so already as well.
    And lastly, you sure all your code's published to the server? If you're still stuck, then the best thing to do is to make this page as simple as possible, put just 1 checkbox w/o all the table/repeats/etc. to help you eliminate other possibilities.
    Sorry can't be more helpful...

  • Listening events on another class

    Hi, I am doing a program that uses differents jpanels, So I need to set a button enabled when an event ocurrs in another panel, how can I do that. the problem is that the panel from wich I need to listen is another class.
    please can someone help me posting some small code that shows how can I listen events on other classes. I think I am able to detect it changing a static variable on another class and having a thread that verify its state, But i dont want to do that, I want to use a listener or any other similar way.

    there's a lot of ways so it depends on the architecture of your program.
    here's a couple of ideas to play with.
    import javax.swing.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    public class MyFrame extends javax.swing.JFrame {
        public MyFrame(AnotherClass a) {
            JButton b1 = new JButton("OK");
            b1.addActionListener(a);
            JButton b2 = new JButton(a.getButtonAction("Cancel"));
            getContentPane().setLayout(new java.awt.FlowLayout());
            getContentPane().add(b1);
            getContentPane().add(b2);
            setLocationRelativeTo(null);
            pack();
            addWindowListener(new WindowAdapter(){
               public void windowClosing(WindowEvent we){
                   System.exit(0);
        public static void main(String[] args){
            new MyFrame(new AnotherClass()).setVisible(true);
    import javax.swing.Action;
    import javax.swing.AbstractAction;
    import java.awt.event.*;
    public class AnotherClass implements ActionListener {   
        private Action a;//cancel action
        public AnotherClass() {}
        private void setEnabled(boolean b){
            a.setEnabled(b);
        //cancel action
        public Action getButtonAction(String name){
            a =  new AbstractAction(name){
               public void actionPerformed(ActionEvent ae){
                   System.out.println("Cancel");
            return a;
        public void actionPerformed(ActionEvent e) {
            //ok button action
            System.out.println("okay");
    }

  • Listening events for numeric keys

    Hi,
    How can I listen events for numeric keys without using Canvas?
    I mean I would like to take some actions when user writes something
    on a TextField. My main class is not inherited from Canvas and because of that
    I can't use keyPressed() method to handle these numeric keys.
    Is there a way to handle these events in commandAction() method?

    Hi,
    If u r concerned only about the texfields and if you are using MIDP 2.0 compatible device then try ItemCommandListener.

  • Help Please ... with calling functions inside listener events

    I need the window to update itself before another method inside my listener is called. When I make the call to updateUI() it preforms it's function once my listener event is compelete while I would like to to happend.
    paw.updateHasMoved();
    temp.updateUI();// -->Want the update to occure before the next line is called
    piece.CB.board = ComputersMove(piece.CB.board);

    okidoi Mr Helpy!
    let me try with this
    just one more question, the button should be created at
    runtime or inside my
    movieclip?
    Regards
    Rick
    "Mr Helpy mcHelpson" <[email protected]>
    escribió en el mensaje
    news:f46tjk$lg1$[email protected]..
    > flooring.onLoad = function(success) {
    > if (flooring.firstChild.hasChildNodes()) {
    >
    > you can just do
    >
    > flooring.onLoad = function(success) {
    > if (success) {
    >
    > you'll need to create a button on top of your image.
    This for me is most
    > easily done with a predefined custom class, and on the
    instantiation of
    > your
    > image(movieclip) you can define the button actions
    contained in the movie
    > clip.
    >
    > make sense?
    >
    > HmcH
    >

  • [JS - CS5] listen events on the title bar of a palette

    I want to listen click on the title bar of a palette.
    I use
    myWin.addEventListener ("click",myFunction);
    but it works only on the bounds area, not on the title bar.
    Is it possible to listen events on the title bar?
    thanks
    Ivan

    I want to listen click on the title bar of a palette.
    I use
    myWin.addEventListener ("click",myFunction);
    but it works only on the bounds area, not on the title bar.
    Is it possible to listen events on the title bar?
    thanks
    Ivan

  • Listening events in another class in a another folder

    Listening events in another class in a another folder
    Is there away of controlling a event from another location without being in the same directory/location.
    I've got a button made and a Event Action for the button made in two seperate classes. But I can't make them work without placing them both in the same location together.
    Any simple code that help communicate of long distances/folders.
    Thankyous.

    The "distance" should not be an issue, only visibility. The class that contains the button need to implement some public method of adding an ActionListener to the button. Of course the class that implements the action listener would have to have access to the instance of the button class to call that method.
    Class A {
    private JButton myButton;
    public void addActionListenerToButton (ActionListener listener){
       myButton.addActionListener (listener);
    }

  • How do i hide/cancel popup on fetch  listener event

    Hi,
    I have a popup.  popup should not be visible  if there is any database error
    raise on execution of procedure which call inside popup fetch listener

    hi user,
    I have a popup.  popup should not be visible.
    there is lot of ways to rendering or no rendering of popup. why you want to listener event?
    if there is any database error
    what you mean db error. what kind it is.
    raise on execution of procedure which call inside popup fetch listener
    I did not know about your requirement. by blindly read this i can't  able to come to conclusion.
    please give enough info about jdev? and usecase?. and so on.

  • Java 2 console event handling

    Hi all,
    Is there any way to handle the console events? I need something like AWT's WindowListener but for handling console events - "on close" in particular. I've written basic server app for a game, and it does not have gui (it only listens on specific port and sends messages from point A to point B). As usually on any Java app launch I get a console window (if not disabled of course...). The problem is, when I shut down the server, users don't get notified that the server was shut down, and they "loose" connection with each other without knowing it. So, I need an event listener which would catch the "On Close" or "On Exit" event of the console window when I press the "X" and CTRL+C to close server, where I would add code to send messages to all users to inform off server offline status.
    Any help would be greatly appreciated,
    Oleg

    thanks, acneto. But then again, I would need a listener for keys for console events? Is there one? But even if there is, users won't bother themselves typing anything (they will have the server app too), they'll just close it by pressing the "X" or CTRL+C, and other users won't get notified, so it's better to have a console window listener or something... Well, if this is not possible then I guess it'll be easier to just create a simple gui and then I'd add usual AWT listener... just curious anyways. If anyone has any other suggestions, I'd gladly hear them.
    Oleg

  • Air Native Extension - Java Key Listener

    Hello all,
    Firstly I'd like to thank you for creating an excellent and helpful community. I have an issue I have been stuck on for around 2 weeks now.
    I am creating an android native extension to listen to key input from a proprietary remote control device. GameInput does not recognise it as a game controller so we have to create a native extension to get the input. I have it working fully except for one issue; if the game loses context (eg the user gets a phone call or the game goes into the background for any other reason) I do not get any other input.
    The way I am doing it is to attach an onKeyListener to the currently focused View (an AirWindowSurfaceView). This works perfectly, but when the context is lost I'm assuming the AirWindowSurfaceView changes and I cannot find a way to get a reference to the new one. Here is my key listener setup code (from the native Java):
    public void updateListeners()
        if(_view != null)
          _view.setOnKeyListener(null); //remove from the old view
          _view.setOnGenericMotionListener(null);
        _context.dispatchStatusEventAsync(_view.toString(), "view"); //send the current view details
        _view = _context.getActivity().getCurrentFocus();  //set the new view
        _context.dispatchStatusEventAsync(_view.toString(), "view");
       if(_onKeyListener == null)
           _onKeyListener = new NativeGamepadKeyListener(_context, this); //create new key listener
       if(_onGenericMotionListener == null)
           _onGenericMotionListener = new NativeGamepadMotionListener(_context, this); //create a new motion listener
       _view.setOnKeyListener(_onKeyListener);          //set on the new view
       _view.setOnGenericMotionListener(_onGenericMotionListener);
    This updateListeners function is called when I get a focus change event on the current view (attached in a similar way) but this doesn't seem to keep it up to date with the current View.
    Please note I'm a newbie at making extensions like these and might be going about it totally the wrong way - if I am and you have any suggestions as to the best way to use an onKeyListener in a native extension I'd love to hear it.
    Thanks in advance for your help!

    I am not able to solve this yet. Is anybody else facing this this problem.

  • How do I resolve connection error with Java API listener?

    I have created a listener using the new Java API (see How do I implement a listener using new MDM Java API? for background). When I run it, I get this error message
    Mar 19, 2008 3:57:58 PM com.sap.mdm.internal.net.ConnectionImpl finalize
    INFO: Disconnect was not called. Cleaning up connection in finalize.
    This message is triggered whenever I generate a data event that I would otherwise expect to be captured and handled by the listener. I have tried a number of things, including setting the connection to NO_TIMEOUT and trying SimpleConnection versus ConnectionPool, but always with the same result.
    Here is some sample code for the listener:
    public class DataListenerImpl implements DataListener {
         public void recordAdded(RecordEvent evt) {          
              System.out.println("===> Record Added Event");
              System.out.println(evt.getServerName());
         public void recordCheckedIn(RecordEvent evt) {
              System.out.println("===> Record Checked In Event");
              System.out.println(evt.getServerName());          
         public void recordCheckedOut(RecordEvent evt) {
              System.out.println("===> Record Checked Out Event");
              System.out.println(evt.getServerName());               
         public void recordModified(RecordEvent evt) {
              System.out.println("===> Record Modified Event");
              System.out.println(evt.getServerName());
    And here is the code for the Event Dispatcher:
    public void execute(Repository repository) {
         DataListener listener = new DataListenerImpl();
         try {
              EventDispatcherManager edm = EventDispatcherManager.getInstance();
              EventDispatcher ed = edm.getEventDispatcher(repository.getServer().getName());
              ed.addListener(listener);
              ed.registerDataNotifications(SystemProperties.getUserName(), SystemProperties.getPassword(),
                        repository.getIdentifier(), repository.getLoginRegion());
              ed.registerRepositoryNotifications(SystemProperties.getUserName(), SystemProperties.getPassword(),
                        repository.getIdentifier());
              ed.registerGlobalNotifications();
              while (true) {
                   Thread.yield();
                   try {
                        Thread.sleep(1500);
                   } catch (InterruptedException ex) {
                        System.out.println("Interrupted Exception: " + ex.getMessage());
         } catch (ConnectionException e) {
              e.printStackTrace();
         } catch (CommandException e) {
              e.printStackTrace();
    Has anyone else encountered this message? Could it be related to a TCP configuration on the server? Or is this a bug in the Java API?
    As I mentioned in the forum posting linked to above, I have not encountered this problem with the MDM4J API.
    Any help is greatly appreciated.

    I resolved it. We are switching over to SP6, Patch 1 and the listener code works fine with this version of the Java API.
    Just one thing to note, though: make sure that you register data notifications through MetadataManager in your initialization code:
    metadataManager.registerDataNotifications(userSessionContext, repositoryPassword);
    For information on the changes to the SP6 Java API, especially with regard to connecting to MDM with the UserSessionContext, please review Richard LeBlanc's [presentation|https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/20073a91-3e8b-2a10-52ae-e1b4a10add1c].

  • Java 8 & listening to greetings in UNITY 9.1

    Cisco Unity Connection v9.1.2ES46.12900-46  Java 8 Update 25
    Looks like adding the server dns or IP to the exception list does not do the trick to allow the "Play/Record" button to work when listening to greetings within Unity Connection. Tried every browser and java setting..  Any workaround for this? 

    And that doesn't work half the time either.  This has to be one of the weakest parts of Unity.  I have had multiple TAC cases open on this at different times and always end up uninstalling java and reinstalling 3 or 4 different versions then it magically works.  Only for the next time you go to use the greeting or message play back to not work.   I think last time I had to go back to Java 6 release 45 or something like that.

  • How to listen Events in subclasses

    Hello, I'll try to be as clear as possible.
    I've two AS2 classes, say Main and Sub.
    Sub inherits from Main.
    Main gets instantiated by Sub by calling super in its
    constructor.
    In Sub constructor a Main method gets invocated too.
    Being this Main method related to a remoting call, it
    automatically
    calls a fault or a result event when it receives data from
    the server.
    In the Result function I put:
    dispatchEvent({type:'myMessage', target:this});
    What I'm trying to do:
    this message should be listened by Sub.
    When Sub receives this event it should fire one of its
    methods.
    How to do this?
    Thanks!

    Sorry. This doesn't make sense. Please rephrase the question or try posting in your native language.

  • Dispatching and listening events in different swf in flex

    I have two swf files.
    1.Main Application swf file.
    2.Module swf file
    If i dispatch an event in main application swf file i am unable to listen in module swf file.
    Can any one propose me a solution for this.

    You can use this example:
       private function ready(event:ModuleEvent):void
        var c:UIComponent = event.currentTarget.child as UIComponent;
        c.addEventListener(events.system_events.MODULE_UPDATED, updated, false, 0, true);
    <mx:ModuleLoader id="mod" x="0" y="0" ready="ready(event);" error="load_error(event);" width="100%" height="100%" />

  • Cannot listen event

    I found that if I have some time consuming tasks performed in
    one handler. Another event cannot be listened.
    public function eventhandler1(event:event1):void
    time consuming tasks
    public function eventhandler2(event:event2):void
    sth actions
    If event1 occurs first, the actions in eventhandler2 will
    never be performed.
    how can I resolve the problem?
    Thanks.
    Gavin

    My handlers listen to different events and I assigned
    priorities to them.
    Actually, I am handling the socket event.
    The data which I receive from socket is quite large.
    And I need to extract and sort the data before another
    reading of bytestream from socket.
    When my program is extracting data, it is not able to listen
    the socket event.
    public function DataExtractHandler(event:DataEvent):void
    a loop to extract data from buffer
    public function SocketEventhandler(event:SocketEvent):void
    read bytestream from socket to buffer
    }

Maybe you are looking for