回答編集履歴
1
1クラスにまとめた
test
CHANGED
@@ -81,3 +81,84 @@
|
|
81
81
|
|
82
82
|
通常GUIプログラムではコンソール入出力は使用しません。
|
83
83
|
UI部品(コンポーネント)を使って、簡単に操作できるようにしましょう。
|
84
|
+
|
85
|
+
---
|
86
|
+
|
87
|
+
追記
|
88
|
+
1クラスにまとめました。これなら間違いなく実行できるでしょう^^
|
89
|
+
|
90
|
+
```Java
|
91
|
+
import javax.swing.*;
|
92
|
+
import java.awt.Color;
|
93
|
+
import java.awt.Graphics;
|
94
|
+
import java.util.Scanner;
|
95
|
+
|
96
|
+
public class Test1 extends JPanel {
|
97
|
+
public static void main(String[] args) {
|
98
|
+
Scanner stdIn = new Scanner(System.in);
|
99
|
+
int n;
|
100
|
+
while (true) {
|
101
|
+
System.out.println("正何角形?3-999:");
|
102
|
+
try {
|
103
|
+
n = stdIn.nextInt();
|
104
|
+
if (3 <= n && n <= 999) break;
|
105
|
+
} catch (Exception ignored) { stdIn.next(); }
|
106
|
+
}
|
107
|
+
|
108
|
+
JFrame gw = new JFrame("円と正多角形");
|
109
|
+
gw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
110
|
+
gw.setSize(1000, 1000);
|
111
|
+
gw.setLocationRelativeTo(null);
|
112
|
+
|
113
|
+
gw.add(new Test1(n));
|
114
|
+
gw.setVisible(true);
|
115
|
+
}
|
116
|
+
|
117
|
+
private int n;
|
118
|
+
|
119
|
+
public Test1(int n) {
|
120
|
+
this.n = n;
|
121
|
+
printApproximationPI();
|
122
|
+
|
123
|
+
SpinnerNumberModel model = new SpinnerNumberModel(n, 3, 999, 1);
|
124
|
+
JSpinner spinner = new JSpinner(model);
|
125
|
+
spinner.addChangeListener(e -> {
|
126
|
+
this.n = (int) spinner.getValue();
|
127
|
+
repaint();
|
128
|
+
printApproximationPI();
|
129
|
+
});
|
130
|
+
add(spinner);
|
131
|
+
}
|
132
|
+
|
133
|
+
@Override public void paintComponent(Graphics g) {
|
134
|
+
super.paintComponent(g);
|
135
|
+
|
136
|
+
int x0 = getWidth() / 2;
|
137
|
+
int y0 = getHeight() / 2;
|
138
|
+
int r = Math.min(x0, y0) / 5 * 4;
|
139
|
+
|
140
|
+
g.setColor(Color.BLUE);
|
141
|
+
g.drawOval(x0 - r, y0 - r, r * 2, r * 2);
|
142
|
+
|
143
|
+
|
144
|
+
int[] x = new int[n];
|
145
|
+
int[] y = new int[n];
|
146
|
+
double delta = 2 * Math.PI / n;
|
147
|
+
|
148
|
+
for (int i = 0; i < n; i++) {
|
149
|
+
x[i] = (int) (Math.cos(-Math.PI / 2 + delta * i) * r) + x0;
|
150
|
+
y[i] = (int) (Math.sin(-Math.PI / 2 + delta * i) * r) + y0;
|
151
|
+
}
|
152
|
+
g.setColor(Color.RED);
|
153
|
+
g.drawPolygon(x, y, n);
|
154
|
+
}
|
155
|
+
|
156
|
+
private void printApproximationPI() {
|
157
|
+
double a = n;
|
158
|
+
double b = 180 / a;
|
159
|
+
double m = Math.toRadians(b);
|
160
|
+
double l = a * (Math.sin(m));
|
161
|
+
System.out.println("正" + n + "角形の円周率の近似:" + l);
|
162
|
+
}
|
163
|
+
}
|
164
|
+
```
|