Also,
1) Have a look at the Math library in the API. Does it use radians or degrees when calculating sin and cos?
2) You translate your numbers by the radius, but you also need to take into account the translation of your circle by 100 in both x and y directions.
3) Draw on a JPanel and not directly on the JFrame. Override JPanel's paintComponent, not the paint method.
4) Avoid magic numbers and instead use constants or variables. It will make your calcs much easier to debug. For instance,
|
Code:
|
//... code deleted. I didn't like it. |
edit: I hate to give exact solutions, but I'm not sure if you used my previous code which I don't like as it had some unnecessary redundancies. Here is I think a better solution:
|
Code:
|
import java.awt.*;
import javax.swing.*;
public class TestingPoint2 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyGraph2 graph = new MyGraph2();
JFrame frame = new JFrame("Graph");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(graph);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
class MyGraph2 extends JPanel {
private static final int APP_WIDTH = 600;
private static final int RADIUS = 200;
private static final int DELTA_RADIUS = 25;
private static final int OUTER_RADIUS = RADIUS + DELTA_RADIUS;
private static final int CENTER_X = 300;
private static final int CENTER_Y = 300;
private static final int SAFE_P = 60;
private static final int LABEL_FONT_SIZE = 32;
public MyGraph2() {
setPreferredSize(new Dimension(APP_WIDTH, APP_WIDTH));
// one of the few times I recommend absolute/null positioning
setLayout(null);
for (int i = 0; i < SAFE_P; i += 5) {
JLabel label = new JLabel(String.valueOf(i));
label.setFont(new Font(Font.SANS_SERIF, Font.BOLD, LABEL_FONT_SIZE));
Dimension labelSize = label.getPreferredSize();
double radAngle = ((double) i / (SAFE_P)) * Math.PI * 2.0;
int xCor = (int) (CENTER_X + (OUTER_RADIUS * Math.cos(radAngle)));
int yCor = (int) (CENTER_Y + (OUTER_RADIUS * Math.sin(radAngle)));
// To center the label at location
xCor -= labelSize.width / 2;
yCor -= labelSize.height / 2;
label.setSize(labelSize);
label.setLocation(xCor, yCor);
add(label);
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// to create smooth graphics
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int x0 = CENTER_X - RADIUS;
int y0 = CENTER_Y - RADIUS;
int diameter = 2 * RADIUS;
g.drawOval(x0, y0, diameter, diameter);
}
} |