Note that there are some explanatory texts on larger screens.

plurals
  1. POSwing Timer with Graphics component
    primarykey
    data
    text
    <p>I want to creat a circle in on a panel which appears and dissapears every 2 seconds. Here is that i have:</p> <pre><code>public class Board extends JPanel implements ActionListener { private final int DELAY = 2000; private Timer timer; /* * constructor */ public Board() { setFocusable(true); initGame(); } /* * initialize board */ public void initGame() { timer = new Timer(DELAY, this); timer.start(); } public void paint(Graphics g) { super.paint(g); g.setColor(Color.gray); // draw an oval starting at 20,20 with a width and height of 100 and // fill it g.drawOval(20, 20, 100, 100); g.fillOval(20, 20, 100, 100); g.dispose(); } @Override public void actionPerformed(ActionEvent e) { repaint(); } } </code></pre> <p>thank you guys. Now I wanna control my circle. But again something is wrong and it is not moving as I want.</p> <p>here are new methods:</p> <pre><code> private boolean left = false; private boolean right = true; private boolean up = false; private boolean down = false; private Timer timer; public int x = 20; public int y = 20; public int x2 = 100; public int y2 = 100; </code></pre> <p>...</p> <pre><code> public void paint(Graphics g) { super.paint(g); if (drawCircle) { g.setColor(Color.gray); // draw an oval starting at 20,20 with a width and height of 100 and // fill it g.drawOval(x, y, x2, y2); g.fillOval(x, y, x2, y2); } // removes native non-Java recourses g.dispose(); } public void move() { if (left) { x -= 5; } if (right) { x += 5; } if (up) { y -= 5; } if (down) { y += 5; } } @Override public void actionPerformed(ActionEvent e) { move(); repaint(); } private class TAdapter extends KeyAdapter { public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if ((key == KeyEvent.VK_LEFT) &amp;&amp; (!right)) { left = true; up = false; down = false; } if ((key == KeyEvent.VK_RIGHT) &amp;&amp; (!left)) { right = true; up = false; down = false; } if ((key == KeyEvent.VK_UP) &amp;&amp; (!down)) { up = true; right = false; left = false; } if ((key == KeyEvent.VK_DOWN) &amp;&amp; (!up)) { down = true; right = false; left = false; } } } </code></pre> <p>/<strong><em>*</em>**<em>*</em></strong>/ Solved , i just added </p> <pre><code>addKeyListener(new TAdapter()); </code></pre> <p>to my Board constructor!</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.
    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