Note that there are some explanatory texts on larger screens.

plurals
  1. POKeyListeners not responding when added to JFrame
    primarykey
    data
    text
    <p>I've been reading the java documentation and am trying to understand key listeners and their uses. I managed to make a simple program where 'w' and 's' toggled the background colour, however when I tried to make them move a painted ball they stopped responding. I am fairly sure it isn't a painting issue as I read through the JavaDocs common painting issues. I've set the JFrame as focuseable (or at least I think I have). If anyone could point me In the right direction it would be greatly appreciated.</p> <p>Here is the main class</p> <pre><code>import javax.swing.JFrame; import java.awt.EventQueue; public class frame { public static void main(String[] args){ EventQueue.invokeLater(new Runnable() { @Override public void run() { showGui(); } }); } public static void showGui(){ JFrame f = new JFrame("Testing.."); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setFocusable(true); f.add(new Gui()); f.setSize(300,300); f.setVisible(true); } } </code></pre> <p>and the Gui/KeyListener class</p> <pre><code>import java.awt.Color; import java.awt.Graphics; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.BorderFactory; import javax.swing.JPanel; @SuppressWarnings("serial") public class Gui extends JPanel { public Gui(){ HandlerClass handle = new HandlerClass(); setBorder(BorderFactory.createLineBorder(Color.black)); addKeyListener(handle); } int x = 30; int y = 30; public void paintComponent(Graphics g){ super.paintComponents(g); g.setColor(Color.BLUE); g.fillRect(x, y, 20, 20); } private class HandlerClass implements KeyListener{ public void keyTyped(KeyEvent e) { switch (e.getKeyChar()){ case 'w': repaint(x,y+1, 20,20); break; case 's': repaint(x,y-1, 20,20); System.out.println("testing if this fires"); break; } } public void keyPressed(KeyEvent e) { //todo } public void keyReleased(KeyEvent e) { //todo } } } </code></pre> <p>Any pointings in the right direction would be very helpful, thank you.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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