回答編集履歴
5
import java.awt.Rectangleを削除
answer
CHANGED
@@ -1,6 +1,5 @@
|
|
1
1
|
ボタンをクリックしたらランダムな位置に移動するサンプルコードです。
|
2
2
|
```Java
|
3
|
-
import java.awt.Rectangle;
|
4
3
|
import java.util.Random;
|
5
4
|
import javax.swing.JButton;
|
6
5
|
import javax.swing.JFrame;
|
4
moveToメソッドを追加
answer
CHANGED
@@ -12,30 +12,28 @@
|
|
12
12
|
public static void main(String[] args) {
|
13
13
|
SwingUtilities.invokeLater(() -> {new Q107092().setVisible(true);});
|
14
14
|
}
|
15
|
-
private JButton bt;
|
15
|
+
private final JButton bt = new JButton("●");
|
16
|
-
private Random rnd = new java.util.Random();
|
16
|
+
private final Random rnd = new java.util.Random();
|
17
17
|
public Q107092() {
|
18
18
|
// 画面が閉じられなくなることを防ぐため、setDefaultCloseOperationは一番最初に設定。
|
19
19
|
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
20
20
|
setSize(700, 600);
|
21
|
-
setLayout(null);
|
21
|
+
setLayout(null);
|
22
|
-
int xran = rnd.nextInt(650);
|
23
|
-
int yran = rnd.nextInt(550);
|
24
|
-
bt = new JButton("●");
|
25
22
|
bt.addActionListener((e) -> {
|
26
|
-
Rectangle rect = bt.getBounds();
|
27
|
-
rect.x = rnd.nextInt(650);
|
28
|
-
rect.y = rnd.nextInt(550);
|
29
|
-
|
23
|
+
moveTo();
|
30
24
|
//コンポーネントの再配置のみならrepaintよりrevalidate
|
31
25
|
revalidate();
|
32
26
|
});
|
33
|
-
// ボタンのサイズを5➾50に変更
|
34
|
-
|
27
|
+
moveTo();
|
35
28
|
add(bt);
|
36
29
|
}
|
30
|
+
private void moveTo(){
|
31
|
+
int x = rnd.nextInt(650);
|
32
|
+
int y = rnd.nextInt(550);
|
33
|
+
// ボタンのサイズを5➾50に変更
|
34
|
+
bt.setBounds(x, y, 50, 50);
|
35
|
+
}
|
37
36
|
}
|
38
|
-
|
39
37
|
```
|
40
38
|
|
41
39
|
□参考情報
|
3
コメントを追加
answer
CHANGED
@@ -27,6 +27,7 @@
|
|
27
27
|
rect.x = rnd.nextInt(650);
|
28
28
|
rect.y = rnd.nextInt(550);
|
29
29
|
bt.setBounds(rect);
|
30
|
+
//コンポーネントの再配置のみならrepaintよりrevalidate
|
30
31
|
revalidate();
|
31
32
|
});
|
32
33
|
// ボタンのサイズを5➾50に変更
|
2
参考情報にrevalidateを追記
answer
CHANGED
@@ -38,4 +38,5 @@
|
|
38
38
|
```
|
39
39
|
|
40
40
|
□参考情報
|
41
|
-
[java.util.Random#nextInt](https://docs.oracle.com/javase/jp/8/docs/api/java/util/Random.html#nextInt-int-)
|
41
|
+
[java.util.Random#nextInt](https://docs.oracle.com/javase/jp/8/docs/api/java/util/Random.html#nextInt-int-)
|
42
|
+
[JComponent#revalidate](https://docs.oracle.com/javase/jp/6/api/javax/swing/JComponent.html#revalidate())
|
1
参考情報にjava.util.Random#nextIntを追加
answer
CHANGED
@@ -35,4 +35,7 @@
|
|
35
35
|
}
|
36
36
|
}
|
37
37
|
|
38
|
-
```
|
38
|
+
```
|
39
|
+
|
40
|
+
□参考情報
|
41
|
+
[java.util.Random#nextInt](https://docs.oracle.com/javase/jp/8/docs/api/java/util/Random.html#nextInt-int-)
|