I have two classes. I try to move circle. When I type a break
statement in Game.java it draws a circle for me without movement. That's fine. However when I want to move circle(by deleting break
it displays nothing. I dont know how to debug that. I found out program is not going inside paint method when I use while without break;
statement.
Can anybody also tell me the way how to debug problem like that. Thanks in advance
App.java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class App extends JFrame {
App() {
JFrame jf = new JFrame();
JPanel jp = new JPanel();
jf.add(jp);
jp.setLayout(new BorderLayout());
jf.setSize(500, 500);
jf.setTitle("Chain Reactor Game");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
Game game = new Game();
jp.add(game, BorderLayout.CENTER);
MenuBar menuBar = new MenuBar();
jf.setJMenuBar(menuBar.createMenuBar());
}
public static void main(String[] args) {
/*
* oracle recommendation to run swing applications in special thread
* they suggest it during thread implementation
*/
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new App();
}
});
}
}
Game.java
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JPanel;
public class Game extends JPanel {
private static final long serialVersionUID = 1L;
int x = 0;
int y = 0;
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
System.out.println("im goint to filloval now");
g2d.fillOval(x, y, 30, 30);
}
public Game() {
while(true) {
moveBall();
repaint();
try {
System.out.println("inside thread");
Thread.sleep(2000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
break; // if i delete this line it not drawing. Why is that ?
}
}
private void moveBall() {
x = x + 1;
y = y + 1;
}
}
When you leave the
break;
in you have an infinite loop. It will never end, meaning that the lineGame game = new Game();
will never return, meaning that the next line, which adds theGame
to theJPanel
will never run, which is why nothing is drawn on the screen. To get this to work, you need to create the GUI, and then perform the drawing.One way to get this to work is to create a new
Thread
to perform the continual drawing:Alternatively, since you are setting up the GUI on the Swing thread, you could run the drawing on the main thread.