Reputation: 78
Can anyone explain as to why this code doesn't show me a 20 x 20 white oval? I've added comments so you dont have to search too much. I think i'm doing something wrong in the paint method. or is it something else? Here's the code:
public class Dodge extends JFrame{ //EXTENDED JFRAME
public Dodge(){
JPanel panel = new JPanel();
//
panel.setBackground(Color.BLACK); //
//
add(panel); //
setTitle("Dodging game"); //
setDefaultCloseOperation(EXIT_ON_CLOSE); // GUI SETUP
setSize(500, 400); //
setLocationRelativeTo(null); //
setResizable(true); //
}
public void paint(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.WHITE); //THIS METHOD SHOULD GIVE ME AN OVAL
g.fillOval(5, 5, 20, 20);
repaint();
}
public static void main(String[] args){ //
SwingUtilities.invokeLater(new Runnable() { // MAIN THREAD
@Override //
public void run() {
new Dodge().setVisible(true); //
Im a beginner so please be clear as to what's wrong
Also please explain as to how this method causes changes in the program when i haven't even called it?
Upvotes: 1
Views: 2648
Reputation: 14448
paint()
method is automatically called when a Component is rendered.
Your oval is not getting displayed because it's hiding behind the tool bar of the Frame or Title bar. (The top one what ever you call it).
Change your fillOval to g.fillOval(50, 50, 20, 20);
and you will see it.
Also, you should always call super.paint(g)
if your overriding it.
Also, don't call repaint()
from your paint()
method.
Upvotes: 4