Первое, что нужно изменить, это сделать JFrame
видимым, добавив setVisible(true);
в его конструктор.Рекомендуется использовать имена, которые имеют четкое значение, чтобы сделать код более читабельным.Сделайте область действия полей максимально ограниченной, в этом случае сделайте их приватными:
private int сenterX, centerY, radius;
(x, y и p являются переменными метода и не должны быть полями)Избегайте использования магических чисел .Вместо этого используйте константы:
private static final int W = 1000, H = 1000, DOT_SIZE =2 ;
Соберите их вместе, используя правильные Соглашения об именах Java и исправьте алгоритм:
import java.awt.Graphics; //add imports to make tour code mcve
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
class DrawFrame extends JFrame {
private final int сenterX, centerY, radius;
private static final int W = 1000, H = 1000, DOT_SIZE =2 ;
DrawFrame(int radius, int centerX, int centerY) {
setSize(W, H);
setTitle("circle drawing algo");
this.radius = radius;
сenterX = centerX;
this.centerY = centerY;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//make program stop when closing frame
setVisible(true); //make frame visible
}
@Override
public void paint(Graphics g) {
super.paint(g);
circl(g);
}
public void circl(Graphics g) {
int x, y;
x = сenterX - radius;
while (x <= сenterX + radius) {
//calculate x
y = (int)Math.sqrt(radius*radius - (сenterX -x)*(сenterX -x ));
g.drawOval(x, centerY-y, 2, 2); // 2 y values for every x
g.drawOval(x, centerY+y, 2, 2);
x++;
}
}
// add main to make your code mcve
public static void main(String[] args) {
SwingUtilities.invokeLater(()-> new DrawFrame(100, 400, 400));
}
}
Следующим улучшением может стать рефакторинг, такрисование выполняется на JPanel
, а не на JFrame
, используя Graphics.drawOval
:
class DrawFrame extends JFrame {
DrawFrame(int radius, int centerX, int centerY) {
setTitle("circle drawing algo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//make program stop when closing frame
add(new DrawingPane(radius, centerX, centerY));
pack();
setVisible(true); //make frame visible
}
// add main to make your code mcve
public static void main(String[] args) {
SwingUtilities.invokeLater(()-> new DrawFrame(100, 400, 400));
}
}
class DrawingPane extends JPanel{
private final int сenterX, centerY, radius;
private static final int W = 1000, H = 1000, DOT_SIZE =2 ;
DrawingPane(int radius, int centerX, int centerY) {
setPreferredSize(new Dimension(W, H));
this.radius = radius;
сenterX = centerX;
this.centerY = centerY;
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawOval(сenterX, centerY, radius, radius);
}
}