KeyListener on JPanel randomly unresponsive

前端 未结 2 1283
夕颜
夕颜 2021-01-15 10:33

I\'m having trouble with the default Java KeyListener in my project. I noticed that the KeyListener doesn\'t seem to get KeyEvents forwarded sometimes when I start.

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-15 11:03

    Don't know if this is related to your problems, but due to the intermittent nature of it perhaps it is...You should execute setVisible() last and in the swing thread. You could call setSize after setVisible if you want to, but the user might see a flicker and it likewise should be done in the swing thread. Do this as your last step:

    SwingUtilities.invokeLater( new Runnable() {
       public void run() {
          window.setVisible( true );
       }
    } );
    

    To do this, you will also need to make window declaration final:

    ...
    final JFrame window = new JFrame();
    ...
    

提交回复
热议问题