I am trying to draw a circle with the press of a button in java. I put the System.out.println() inside the action method to make sure my code was working. The println shows up but no circle drawing anywhere. Any Suggestions? Thank you
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class CircleViewer {
public static void main(String[] args)
{
CircleComponent circle = new CircleComponent();
JButton button = new JButton("Draw");
final JPanel panel = new JPanel();
panel.add(button);
JFrame frame = new JFrame();
class addActionListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
CircleComponent component = new CircleComponent();
String x = JOptionPane.showInputDialog("X Coordinate", "Enter an x coordinate");
int xCoord = Integer.parseInt(x);
String y = JOptionPane.showInputDialog("Y Coordinate", "Enter a y coordinate");
int yCoord = Integer.parseInt(y);
String width = JOptionPane.showInputDialog("Radius", "Enter the length of the radius");
int radius = Integer.parseInt(width);
component.setLocation(xCoord,yCoord);
component.getWidth(radius);
panel.add(component);
System.out.println("CLICKED!");
}
}
frame.add(panel);
ActionListener action = new addActionListener();
button.addActionListener(action);
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
/**
This component lets the user draw a circle by clicking
a button.
*/
public class CircleComponent extends JPanel
{
private int x;
private int y;
private int width;
Ellipse2D.Double circle;
public CircleComponent()
{
circle = new Ellipse2D.Double(x, y, width, width);
}
public Dimension getPreferredSize()
{
return new Dimension(500,500);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.draw(circle);
}
public int getWidth(int aWidth)
{
width = aWidth;
return width;
}
}