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.
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:
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 thepaint(...)
method is not only responsible for painting a component but also its borders and children, this will prevent you from causing problems whenpaint(...)
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.super.paintComponent(g)
method within your JPanel'spaintComponent
override. This will allow Swing to erase images that need to be erased.