Note that there are some explanatory texts on larger screens.

plurals
  1. POJava moving a circle in a gui with arrow keys
    primarykey
    data
    text
    <p>I am trying to move a circle left with a keyEvent. So far, the circle is drawn on the window but it does not move left! I feel like the problem is where I add the Window() constructor to the container. The is no output on the console to tell me that it is working. So I dont think it even reaches the KeyEvent class. Here is my code:</p> <pre><code>import java.awt.*; import java.awt.event.*; import java.awt.geom.Ellipse2D; import javax.swing.*; public class Window extends JPanel { private static Ellipse2D.Double circle; public Window() { super(); int width = 400; int height = 400; circle = new Ellipse2D.Double(0.5 * width, 0.9 * height, 0.1 * width, 0.05 * height); addKeyListener(new MoveCircle()); } @Override protected void paintComponent(Graphics g) { super.paintComponents(g); Graphics2D brush = (Graphics2D) g; int width = getWidth(); int height = getHeight(); g.clearRect(0, 0, width, height); brush.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); brush.draw(circle); } public class MoveCircle implements KeyListener { @Override public void keyPressed(KeyEvent e) { System.out.println("Working on top!"); if (e.getKeyCode() == KeyEvent.VK_LEFT) { System.out.println("Working on bottom!"); circle.x++; repaint(); } } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } } public static void main(String[] args) { Window window = new Window(); JFrame frame = new JFrame(); Container container = frame.getContentPane(); container.add(new Window()); frame.addKeyEvent(window.new MoveCircle()); frame.setSize(800, 700); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setVisible(true); } } </code></pre>
    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.
 

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