I have ventured into the lands of java for the first time and i am starting with a simple pong game, the problem is that when i draw the ball and set the coordinates to move in a loop, the ball that is drawn on the screen won't show at the new coordinates (wont repaint). I know that i have to repaint the JPanel but i can't figure out what is wrong with my code. This is a java application not applet(don't know if it matters) P.S if you have any other suggestions please say so, because i'm not very advanced in correct ways to do stuff Code: import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; public class mainclass extends JPanel implements Runnable { int x, y; public static void main(String[] args) { JFrame f = new JFrame("area to draw"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainclass p = new mainclass(); f.add(p); f.setSize(200, 200); f.setVisible(true); Thread t1 = new Thread(new mainclass()); t1.start(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.CYAN); g.fillOval(x, y, 10, 10); } @Override public void run() { while (true) { //just threw in the print to make sure that the point were updating, which they are System.out.println("new" + x + y); x = x + 1; y = y + 1; this.repaint(); try { Thread.sleep(1000); } catch (InterruptedException e) { } } } } Thanks in advance
hi Steve, I'm no java programmer (My forte is C and Pascal) but perhaps you might want to implement some kind of double buffering scheme. Take a look at this link. http://www.realapplets.com/tutorial/DoubleBuffering.html Hope it helps... :Miki.
since i have posted this i have accomplished my pong game using a screenmanager class i found online (EXTREMELY USEFUL) it implements an excelent double buffering scheme and uses a different method to repaint, however i will leave my original question up because i believe that that code should work and i still would like to know why it doesnt
@steve: A listener is a way of handling events. I think you would create a listener, and when you want to update the screen (paint) you can send a notification message to the listener (which will update the screen) It might be an automatic mechanism as well. I'm not a Java programmer, but We had event handlers in Delphi and we have a similar mechanism in Objective C. Here's a tutorial. http://docs.oracle.com/javase/tutorial/uiswing/events/index.html Hope this helps. :Miki.
yes i understand what a listener does but the paintComponent is a built in method of a java panel so when i call repaint() it should update the panel (but it didn't so i was confused)