このソースで
java
1import java.awt.*; 2 3//メインのクラス 4public class SwingIconMove2{ 5 int width, height; //縦横サイズ 6 Frame mainF; //フレーム 7 Canvas mainC; //キャンバス 8 9 public SwingIconMove2(){ 10 //サイズ設定して 11 width = 500; 12 height = 500; 13 14 //キャンバスの大きさと背景色を指定 15 mainC = new MainCanvas(); 16 mainC.setSize(400,400); 17 mainC.setBackground(Color.blue); 18 19 //フレームの大きさと背景色を指定、キャンバスをフレームに載せる 20 mainF = new Frame("moving ball"); 21 mainF.setBackground(Color.white); 22 mainF.setSize(width,height); 23 mainF.setLayout(new FlowLayout()); 24 mainF.add(mainC); 25 26 mainF.setVisible(true); 27 } 28 29 public static void main(String[] args){ 30 //main関数でインスタンス化を行います 31 SwingIconMove2 frame = new SwingIconMove2(); 32 } 33} 34 35 36class MainCanvas extends Canvas implements Runnable{ 37 int x, y; //ボールの位置 38 int vx = 30; //移動量 39 int vy = -20; //移動量 40 Thread thread; //スレッド準備 41 42 //コンストラクタは位置を指定してスレッド開始 43 public MainCanvas(){ 44 x = 170; 45 y = 265; 46 47 thread = new Thread(this); 48 thread.start(); 49 } 50 51 public void paint(Graphics g){ 52 g.setColor(Color.white); 53 g.fillOval(x, y, 30, 30); 54 } 55 56 public void run(){ 57 while (true) { 58 x += vx; 59 y += vy; 60 61 repaint(); 62 63 64 //早すぎて困るのでスリープ 65 try { 66 Thread.sleep(540); 67 } catch (InterruptedException e) { 68 e.printStackTrace(); 69 } 70 } 71 } 72} 73
このように動きます。
回答2件
あなたの回答
tips
プレビュー