Note that there are some explanatory texts on larger screens.

plurals
  1. POKey Listener doesn't work in a JFrame when traversing from another JFrame
    text
    copied!<p>I have 2 classes. </p> <p>One extends canvas and inside creates a jframe and add the canvas to that jframe and add another keyadapter class to receive key events. I also have main function to test the code. When running from main, the form is displayed and recieves key events too. </p> <p>Now i create another class that extends jframe and implements keylistener to receive events in this form. </p> <p>Once the functionality done in the second class i want to close the second form and show the first form. When showing it from the key event functions in the second class the first class key listener is not working. </p> <p>Please just have a glimpse at my code and tell me how to correct my prob. Thanks for your time and valuable suggestion.</p> <p><strong>Class 1</strong></p> <pre><code>public class Test extends Canvas { private JFrame container; public Test() { container = new JFrame("Space Invaders"); JPanel panel = (JPanel) container.getContentPane(); panel.setPreferredSize(new Dimension(screenSize.width, screenSize.height)); panel.setLayout(null); setBounds(0, 0, screenSize.width, screenSize.height); panel.add(this); container.pack(); container.setResizable(false); container.setVisible(true); try { addKeyListener(new KeyInputHandler(this)); } catch (Exception e) { e.printStackTrace(); } requestFocus(); } private class KeyInputHandler extends KeyAdapter { public void keyPressed(KeyEvent e) { //Some Action } public void keyReleased(KeyEvent e) { //Some Action } public void keyTyped(KeyEvent e) { //Some Action } } public static void main(String args[]){ //Running this canvas here works perfectly with all added keylisteners } } </code></pre> <p><strong>Class 2</strong></p> <pre><code>public class Sample extends JFrame implements KeyListener { public Sample() { init(); this.setSize(100, 100); this.setVisible(true); Sample.this.dispose(); // Created a window here and doing some operation and finally redirecting // to the previous test window. Even now the test window works perfectly // with all keylisteners new Test(); } public static void main(String[] args) { new Sample(); } private void init() { addKeyListener(this); } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { removeKeyListener(this); Sample.this.dispose(); // But when calling the previous Test window here, the window // gets displayed but the keylistener is not added to the // window. No keys are detected in test window. new Test(); } @Override public void keyReleased(KeyEvent e) { } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload