Trying to draw a circle in Java using variable in parameters

*爱你&永不变心* 提交于 2019-12-13 18:21:59

问题


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:


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.


来源:https://stackoverflow.com/questions/18721612/trying-to-draw-a-circle-in-java-using-variable-in-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!