Trying to draw a circle in Java using variable in parameters

3.4k views Asked by At

I am having trouble doing a rather simple task of taking in the diameter of a circle and then drawing it. Here is my code so far.

import javax.swing.*;
import java.awt.Graphics;

public class Shapes extends JFrame
{
    double diameter;

    public Shapes()
    {
        setSize(600,600);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }


    public void getDiameter()
    {
        String input = JOptionPane.showInputDialog("What is the diameter of the circle?");
        diameter = Double.parseDouble(input);

        Shapes gui = new Shapes();
        gui.setVisible(true);
    }

    public static void main(String[] args) 
    {       
        Shapes app = new Shapes();
        app.getDiameter();
    }

    public void paint(Graphics canvas)
    {
        canvas.drawOval(50, 50, (int)diameter, (int)diameter);
    }

}

When I run it, it brings up the Jframe window, but nothing is drawn, so I'm guessing the value of diameter is never passed to the paint method. Can someone help me get this to work? Thanks.

1

There are 1 answers

1
Hovercraft Full Of Eels On BEST ANSWER

Your program is creating two Shapes objects actually, one of which has the diameter field set correctly but is not being displayed, and the other, which retains diameter's default value of 0 and which is displayed.

Suggestions:

  1. Don't draw directly in a JFrame, but rather in the paintComponent(Graphics g) method override of a JPanel that is held by and displayed in the JFrame. There are many reasons for this, but for one, since the paint(...) method is not only responsible for painting a component but also its borders and children, this will prevent you from causing problems when paint(...) tries to paint a GUI's children and borders. It also will help your animations (which surely you will be doing soon) to be smooth given Swing component's default use of double buffering.
  2. Always call the super.paintComponent(g) method within your JPanel's paintComponent override. This will allow Swing to erase images that need to be erased.
  3. Don't create two Shapes objects, but rather only one. This will simplify things greatly and will allow you to set the diameter value of the one and only object of importance.
  4. After changing the diameter field's value, call repaint on your GUI so that the displayed JPanel's paintComponent will be called.