
Patrick B. answered 08/02/20
Math and computer tutor/teacher
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.Color;
public class DrawRect extends JPanel {
private static final int RECT_X = 200;
private static final int RECT_Y = RECT_X;
private static final int RECT_WIDTH =200;
private static final int RECT_HEIGHT = RECT_WIDTH;
private int radius;
private int centerX;
private int centerY;
@Override
protected void paintComponent(Graphics g)
{
//inputs circle radius and center
String inbuff=null;
while (inbuff==null)
{
inbuff = JOptionPane.showInputDialog(null,"Please input the radius of the circle :>");
}
radius = Integer.parseInt(inbuff);
inbuff=null;
while (inbuff==null)
{
inbuff = JOptionPane.showInputDialog(null,"Please input Center x :>");
}
centerX = Integer.parseInt(inbuff);
inbuff=null;
while (inbuff==null)
{
inbuff = JOptionPane.showInputDialog(null,"Please input Center Y :>");
}
centerY = Integer.parseInt(inbuff);
super.paintComponent(g);
// draw the rectangle here
g.drawRect(RECT_X, RECT_Y, RECT_WIDTH, RECT_HEIGHT);
// center of circle is inside the rectangle
if (( centerX>=200) && (centerX<=400) && (centerY>=200) && (centerY<=400))
{
g.setColor(Color.YELLOW);
}
//center of circle is outside the rectangle
if ((centerX<200) || (centerX>400) || (centerY<200) || (centerY>400))
{
g.setColor(Color.GREEN);
}
//center of the circle is ON the rectange
if (
((centerX>=200) && (centerX<=400) && ((centerY==200) || (centerY==400))) ||
((centerY>=200) && (centerY<=400) && ((centerX==200) || (centerX==400)))
)
{
g.setColor(Color.RED);
}
g.fillOval(centerX-radius,centerY-radius,2*radius,2*radius);
}
@Override
public Dimension getPreferredSize() {
// so that our GUI is big enough
return new Dimension(600,600);
}
// create the GUI explicitly on the Swing event thread
private static void createAndShowGui() {
DrawRect mainPanel = new DrawRect();
JFrame frame = new JFrame("DrawRect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
createAndShowGui();
}
});
}
}