エラーも無いのにボールが動かない

このQ&Aのポイント
  • JAVA初心者の質問です。
  • 以下のコードを書いたのですが、ボールが動かない問題に直面しています。
  • エラーメッセージは表示されず、原因が分からず困っています。
回答を見る
  • ベストアンサー

エラーも無いのにボールが動きません

 JAVA初心者です、宜しくお願いします。  今晩は、以下のようなコードを書いてやりましたが、動きません。  何故でしょう、特にエラーははいていません。  原因が分かりません、宜しくお願いします。 =============================================================== public class Ball_1 extends Applet implements Runnable { Thread thr = null; Color BGcolor; int appWidth; int appHeight; int x; int vel; public void inti() { BGcolor = Color.white; appWidth = 400; appHeight = 400; x = 30; vel = 20; } public void paint(Graphics g) { g.setColor(BGcolor); g.fillRect(0,0,appWidth,appHeight); g.setColor(Color.blue); g.fillOval(x,20,100,100); } public void start() { if(thr == null) { thr = new Thread(this); thr.start(); } } public void stop() { if(thr != null) { thr.stop(); thr = null; } } public void run() { while(true) { x = x + vel; if(x > appWidth) { x = x - appWidth; } repaint(); try { thr.sleep(50); } catch(InterruptedException e) { thr.stop(); } } } }

  • Java
  • 回答数3
  • ありがとう数3

質問者が選んだベストアンサー

  • ベストアンサー
  • zozy
  • ベストアンサー率60% (20/33)
回答No.3

例えばですが、 booean move = true; というような変数を宣言し、 public void run(){ while(move){ .... .... if(終了条件に関する判定){ move = false; } } } などというようにし、 また、スレッドを動作させる必要がある場合には thr = new Thread(this); thr.start(); とスレッドの再起動をしましょう。

その他の回答 (2)

  • zozy
  • ベストアンサー率60% (20/33)
回答No.2

stopメソッドを使用してはいけないのは、安全性の問題があるからです。 スレッドでは、スレッド同士の衝突を回避するために、衝突するスレッドを待ち状態にします。 こうすることでスレッドは安全に動作します。 stopメソッドを使用するとそれまで、ロックされていたのが全て解除されます。 つまり、スレッド同士の衝突が起こり放題になるわけです。 銀行の振込みシステムの例   利用者NO   0   1   2 時 |   |   | 間 |   |   | ↓ |   |   |   入金5○ 入金10×入金20× No0以外待ち   |   |   | stopを使うと   利用者NO   0   1   2 時 |   |   | 間 |   |   | ↓ |   |   |   入金5○ 入金10○入金20○ 全員同じ口座に振り込み   |   |   |    2人ほど、損する

htgotk_001
質問者

お礼

 zozyさん、回答有り難うございます    理由はわかりましたが、その場合の書き方は、thr.waitとか そのあとにStopの時間とかを書いてやるのでしょうか。  宜しくお願いします。

  • osamuy
  • ベストアンサー率42% (1231/2878)
回答No.1

(1)必要なパッケージがimportされてない。 (2)「inti」がスペルミス。 ――とか。

htgotk_001
質問者

お礼

 osamuy早速の回答有り難う御座います。    ところで、うまく動いたのですが、エラーではないのですが、thr.stop();の箇所(2箇所とも)で “メソッドstop()は型Threadで使用すべきではありません。”という警告が出ていますが、この意味が分かりません。  どのような意味でしょうか、宜しくお願いします。

関連するQ&A

  • PacMan

    以下のようなプログラムで自動で動くパックマンを作りました。 パックマンが転がっていくのですが、どうしても目の部分の起動がかけません。 どなたかお力を貸していただけないでしょうか? ================================================= import java.applet.Applet; import java.awt.*; import java.awt.event.*; import java.util.*; /* <applet code="PacMan2.class" width="500"height="500"> </applet> */ public class PacMan2 extends Applet implements Runnable { volatile Thread thr; volatile boolean runFlag = true; public void start() { thr = new Thread(this); runFlag = true; thr.start(); } public void stop() { runFlag = false; thr = null; } public void run() { while (runFlag) { repaint(); try { Thread.sleep(1000); //1,000 mili-seconds } catch(InterruptedException e) { runFlag = false; } } } public void paint(Graphics g) { Calendar cal = Calendar.getInstance(); int s = cal.get(Calendar.SECOND); g.setColor(new Color(128,255,255)); g.fillArc(100+s,100,60,60,45-s,300);   g.setColor(new Color(0,0,0)); g.fillOval(130,105,10,10); } } =================================================

    • ベストアンサー
    • Java
  • JavaApplet

    Appletで 円が徐々に大きくなる。 一定の直径を超えるたびに色が変わる。 最大まで大きくなったら、縮んで色を変えながらもとの大きさに戻る。 というのを延々繰り返すものを作りました。 コードは以下です。 import java.applet.*; import java.awt.*; import java.awt.Color; public class project4 extends Applet implements Runnable{ int x; Thread th; public void start(){ th = new Thread(this); th.start(); } public void run(){ while(1==1) { for (x =0; x<=180; ++x) { repaint(); try{ Thread.sleep(100); } catch( InterruptedException e){ } } for (; x>=0; --x) { repaint(); try{ Thread.sleep(100); } catch( InterruptedException e){ } } } } public void paint (Graphics g){ if (x<=18) {g.setColor(Color.blue); } g.fillOval(150,150,20+x,20+x); if ((x >18) && (x<=36)) {g.setColor(Color.darkGray); } g.fillOval(150,150,20+x,20+x); if ((x >36) && (x<=54)) {g.setColor(Color.yellow); } g.fillOval(150,150,20+x,20+x); if ((x >54) && (x<=72)) {g.setColor(Color.green); } g.fillOval(150,150,20+x,20+x); if ((x >72) && (x<=90)) {g.setColor(Color.orange); } g.fillOval(150,150,20+x,20+x); if ((x >90) && (x<=108)) {g.setColor(Color.red); } g.fillOval(150,150,20+x,20+x); if ((x >72) && (x<=108)) {g.setColor(Color.yellow); } g.fillOval(150,150,20+x,20+x); if ((x >108) && (x<=126)) {g.setColor(Color.magenta); } g.fillOval(150,150,20+x,20+x); if ((x >126) && (x<=144)) {g.setColor(Color.orange); } g.fillOval(150,150,20+x,20+x); if ((x >144) && (x<=162)) {g.setColor(Color.cyan); } g.fillOval(150,150,20+x,20+x); if ((x >162) && (x<=180)) {g.setColor(Color.pink); } g.fillOval(150,150,20+x,20+x); } } ここに ボタンを押したら、円の動きがとまる というeventを増やしたいのですが、どうすればよいかアドバイスをいただけませんか。ボタンを使うにはActionListenerを実装しなければならないと思うのですがRunnableと共存はできますか?

    • ベストアンサー
    • Java
  • ボールが勝手に動き困ってます。

    前回にひき続き困ってます>< タイトル画面→(Enterクリック)→ゲーム画面までできたんですが ゲーム画面でボールとタイマーを動かしたくてやってみるとタイマーはうまく いったのにボールが動く速度を変更できず、勝手に動いてしまいます><どう 改善すればいいでしょうか。ソースコードみにくいですが助言お願いします。 import java.awt.Color; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class JavaGame3 { public static void main(String age[]) { JFrame frame = new JFrame(); frame.setTitle("ゲームフレーム"); frame.setSize(500, 550); frame.setLocation(1000, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Testpanel panel = new Testpanel(); frame.add(panel); frame.setVisible(true); } } class Testpanel extends JPanel implements Runnable{ private Ball[] balls; static final int TITLE = 0; static final int GAME = 1; private int mode; private int sec; private Timer timer; private Thread t; public Testpanel() { balls = new Ball[5]; java.util.Random rr = new java.util.Random(); for(int i=0; i<balls.length; i++) balls[i] = new Ball(10*i+6,10*i+31,rr.nextInt(5)+1, rr.nextInt(5)+1); sec = 0; setBackground(Color.black); addKeyListener(new JavaKeyListener()); setFocusable(true); timer = new Timer(1000, new JavaActionListener()); mode = TITLE; t = new Thread(this); } class JavaActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (sec == 30) { timer.stop(); } else { sec++; } } } private void drawTitle(Graphics g) { g.setColor(Color.blue); g.drawString("タイトル", 165, 150); g.setColor(Color.white); g.drawString("Hit Enter Key!", 150, 350); } public void drawGameOver(Graphics g) { g.setColor(Color.white); g.setColor(Color.red); g.drawString(sec + "sec", 230, 300); repaint(); for (int i=0; i<balls.length; i++) balls[i].draw(g); } protected void paintComponent(Graphics g) { super.paintComponent(g); if(mode == TITLE) { drawTitle(g); } else if(mode == GAME) { drawGameOver(g); } } class JavaKeyListener implements KeyListener { public void keyPressed(KeyEvent e){ int key = e.getKeyCode(); if(mode == TITLE) { switch(key) { case KeyEvent.VK_ENTER: mode = GAME; timer.start(); t.start(); sec = 0; break;} } else { switch (key) { case KeyEvent.VK_ENTER: mode = TITLE; break; } }repaint(); } public void keyReleased(KeyEvent e){} public void keyTyped(KeyEvent e){} } public void run() { while(true) { try { Thread.sleep(100); } catch (Exception e) {} repaint(); } } } class Ball { private int x, y, vx, vy, r; public Ball(int x, int y, int vx, int vy) { this.x = x; this.y = y; this.vx = vx; this.vy = vy; r = 30; } public void draw(Graphics g) { g.fillOval(x, y, r, r); x += vx; y += vy; if(x < 0 || x > 457) vx = -vx; if(y < 0 || y > 433) vy = -vy; } }

    • ベストアンサー
    • Java
  • <identifier>エラーについて

    paintメソッド内ではなく、public class直下で図形の表示をしなければならないのですが、どうしても <identifier>がありません とエラーが出てしまいます; 調べてみたのですがわからなかったので指摘をお願いしますorz プログラムは以下の通りです /* <applet code="Reidai25kai.class" width=500 height=600> </applet> */ import java.applet.Applet; import java.awt.*; public class kadaiM extends Applet implements Runnable { int xichi = 100, yichi = 250, xido = 3, yido = 4; int i, mx=225, my=495; int[] bx = {100,150,200,250,300,350, 100,150,200,250,300,350, 100,150,200,250,300,350}; int[] by = {250,250,250,250,250,250, 300,300,300,300,300,300, 350,350,350,350,350,350}; g.setColor(new Color( 0, 255, 0)); g.fillRect(mx, my, mx+50, my+10); g.drawRect(0, 0, 450, 550); for(i=0; i<18; i++) { g.setColor(new Color(255,170,10*i)); g.fillOval(bx[i]-20,by[i]-20,50,50); } public void init() { Thread hyoji; hyoji = new Thread(this); hyoji.start(); } public void run() { for( ; ; ) { try { xichi = xichi + xido; //ボールx座標の更新 yichi = yichi + yido; //ボールy座標の更新 repaint(); if(xichi < 10 || xichi > 440)xido = -xido; //横方向跳ね返り if(yichi < 10 || yichi > 540)yido = -yido; //縦方向跳ね返り Thread.sleep(30); } catch(InterruptedException e){} } } public void paint(Graphics g) { g.setColor(new Color( 0, 0, 255)); g.fillOval(xichi-10, yichi-10, 20, 20); } }

  • java:複数のボールを反射させるプログラム

    大学の課題で、3つのボールが各々の動作でバウンドするプログラムを作れというものが出たのですが、 ボールを1つから3つにする方法がわかりません。 というのも配列を用いれば良いそうなのですが、組み込み方が分かりません。 ボールが1つの場合は import java.awt.*; import java.applet.Applet; public class AnimBall extends Applet implements Runnable{ final int WIDTH=500,HEIGHT=200,DP=10; Thread kick; int xp=DP,yp=HEIGHT/2; public void init(){ setBackground(new Color(230,255,200)); } public void start(){ if(kick==null){ kick=new Thread(this); kick.start(); } } public void run(){ int signx=1,signy=1; while(true){ if(xp>=WIDTH-DP) signx =-1; else if(xp<=DP) signx =1; xp += signx*DP ; if(yp >=HEIGHT-DP) signy= -1; else if(yp<=DP) signy =1; yp += signy*DP; repaint(); try{ kick.sleep(150); }catch(InterruptedException e){ } } } public void paint(Graphics g){ g.setColor(Color.blue); g.fillOval(xp-DP,yp-DP,2*DP,2*DP); } public void stop(){ if(kick != null){ kick=null; } } } というプログラムと、 <html> <head><title>Bouncing Ball</title> </head> <body bgcolor="white"> <h1>Wandering Ball</h1> <applet code="AnimBall.class" width=500 height=200> </applet> </body> </html> で動作することは確認済みです。 課題のヒントとして、 (1)  int[] stepx=new int[3]; をどこかに組み込む。 (2) ボールの位置はxp[i]、yp[i]、方向指定はsignx[i]、signy[i]    ボールの位置の増分を表すために、stepx[i]、stepy[i]を用い、各ボールに独立の動きを与えること。 (3) Math.random()を用いることにより、各ボールの動き(増分)をスタート時点(すなわち、メソッドpublic void init()の中)で乱数で与える事が出来る。 という3点が挙げられています。 なにからなにまで丸投げで申し訳ありませんが 知識のある方お力添えをよろしくお願いいたします。

  • ウインドウを大きくしてもボールの動きが変わらない

     今晩は、java初心者です。  宜しくお願い致します。  "ComponentListener"でウインドウを"componentResized"してもボールの動く範囲 は変わりません、何故でしょうか。    "componentResized"では確かに"Resized"されたウインドウの大きさをとっていますが、 何故かボールの動きには反映されません。  宜しくお願いします。 ======================================================================================== public class Ball2 extends Applet implements Runnable , ComponentListener { public static final long serialVersionUID = 1L ; int width , height ; Thread thread ; boolean  LoopFlag = false  ; int x = 30 , y = 100 ; Image  offScreen ; Graphics screen ; int vx = 2 , vy = 2 ; public void init() { width = getSize().width ; height = getSize().height ; thread = new Thread( this ); thread.start(); offScreen = createImage( width, height ) ; screen = offScreen.getGraphics() ; addComponentListener(this) ; } public void componentResized( ComponentEvent e ) { width = getSize().width ; height = getSize().height ; } public void run() { while( LoopFlag == false ) { move() ; repaint() ; try { Thread.sleep( 10 ) ; } catch ( InterruptedException e ) {} } } private void move() { if( x >= width - 50 ) { vx =- vx ; } if( y >= height - 50 ) { vy =- vy ; } if( x < 0 ) { vx =- vx ; } if( y < 0 ) { vy =-vy ; } x += vx; y += vy; } public void update( Graphics g) { paint(g) ; } public void paint( Graphics g) { screen.clearRect( 0 , 0 , width , height ) ; screen.setColor( Color.blue ) ; screen.fillOval( x , y , 50 , 50 ) ; g.drawImage( offScreen , 0 , 0 , this ) ; } public void destroy() { LoopFlag = true ; } public void componentHidden( ComponentEvent e ){} public void componentMoved( ComponentEvent e ){} public void componentShown( ComponentEvent e ){} }

    • ベストアンサー
    • Java
  • 「初心者です」-Xlint: deprecation

    import java.awt.*; import java.applet.*; public class ani_ball extends Applet implements Runnable { Thread th_mvball = null; int X,Y; double x1,y1; double x2,y2; double dx,dy; Graphics g; public void init() { this.setBackground(new Color(150,245,255)); this.X = 250; this.Y = 250; this.setSize(X,Y); this.x1 = this.x2 = this.X/2; this.y1 = this.y2 = this.Y/2; this.dx = 3; this.dy = 2; } public void paint(Graphics g) { g.setColor(Color.red); g.fillOval((int)(this.x2-3),(int)(this.y2-3),6,6); this.x1 = this.x2; this.y1 = this.y2; } public void start() { if(th_mvball == null) { th_mvball = new Thread(this); th_mvball.start(); } } public void run() { while(true) { try { this.move(); this.repaint(); Thread.sleep(10); } catch(InterruptedException e ) { this.stop(); } } } public void move() { if( y2 > Y ) { y2 = 2*Y - y1 - dy; dy = -dy; } else if ( y2 < 0) { y2 = -y1 - dy; dy = -dy; } else if ( x2 > X) { x2 = 2*X - x1 -dx; dx = -dx; } else if ( x2 < 0) { x2 = -x1 - dx; dx = -dx; } if( x2 < 0 ) { x2 = -x2 ; dx = -dx; } else if ( y2 < 0) { y2 = -y2; dy = -dy; } else if ( x2 > X) { x2 = 2*X - x2; dx = -dx; } else if ( y2 > Y) { y2 = 2*Y - y2; dy = -dy; } x2 = x1 + dx; y2 = y1 + dy; } public void stop() { if(th_mvball!=null) { th_mvball stop(); th_mvball=null; } } } ↑のプログラムをコンパイルすると、「-Xlint: deprecation オプションを指定して再コンパイルしてください」とエラーが出ます。 エラーの対処法、またはプログラムの訂正すべき箇所を教えてください。 よろしくお願いします。

    • ベストアンサー
    • Java
  • 色が変わる文字について

    javaの初心者です。 環境OSWindows2000 使用ソフトjavaBuilder5です。 今回入門書を見ながら作ったのですが、 (写したが正しいかな?) 実行すると文字の後ろの色がグレーになります。 これを変更する方法を教えてください 黒とか赤とかに変更したいのです。 ーーーソースーーー import java.applet.Applet; import java.awt.*; import java.lang.*; public class TopTitle extends Applet implements Runnable{ Thread th=null; String msg="",cen="",def="",aft=""; int no,width,wait; public void init(){ msg=getParameter("MESSAGE"); msg=" "+msg+" "; no=msg.length(); wait=Integer.parseInt(getParameter("WAIT")); } public void update(Graphics g){ paint(g); } public void paint(Graphics g){ Font f=new Font("TimesRoman",Font.BOLD,48); FontMetrics fm=getFontMetrics(f); g.setFont(f); int width=fm.stringWidth(def); g.setColor(new Color(0,0,255)); g.drawString(msg,0,48); g.setColor(new Color(125,125,125)); g.drawString(cen,width,48); } public void start(){ if (th==null){ th=new Thread(this); th.start(); } } public void run(){ int i; while (true){ try{ for(i=0;i<no-1;i++){ def=msg.substring(0,i); cen=msg.substring(i,i+1); th.sleep(1000); repaint(); } th.sleep(wait); } catch(InterruptedException e){} } } public void stop(){ if(th!=null){ th.stop(); th=null; } } }

    • ベストアンサー
    • Java
  • javaのエラーの意味がわかりません、お願いします

    今日は、javaを勉強している初心者です。 以下のコードを書いてやりましたが、「sleep(Graphics)は引数()に適用できません」、「Color.Whiteを解決できません」とエラーがでます、エラーの意味が分かりません。 一体何処が間違っているのでしょうか、宜しくお願いします。 ===================================================================== public class ani_Moving_Ball extends Applet { int x; public void paint(Graphics g) { for(x=0 ; x<180 ; ++x) { clear(g); g.drawOval(x,90,19,19); sleep(); } } public void clear(Graphics g) { g.setColor(Color.White); g.fillRect(0,80,200,40); g.setColor(Color.Black); } public void sleep(Graphics g) { double s=0.0; for (int j=1 ; j<100 ; ++j) { for (int k=1 ; k<100 ; ++k) { s =+ Math.sin((double)j); } } } }

    • ベストアンサー
    • Java
  • javaのJPanel重ね時、repaint

    JPanelの上にJPanelを重ね、上のJPanelを透過させました。 この状態で両方のパネルでstartを行います。 下記の結果では、両方が動いています。 目標として、片方のパネルが描写をのこし、片方のパネルが再描写するのが理想です。 誰かお教えください。 import javax.swing.JFrame; import java.awt.*; public class Test extends Object { public static void main(String[] arguments){ TestViewU Upanel = new TestViewU();//上のパネル TestViewS Spanel = new TestViewS();//下のパネル Upanel.setLocation(new Point(0, 0)); Upanel.setLayout(null); Upanel.setOpaque(false); Spanel.setLocation(new Point(0, 0)); Spanel.setLayout(null); Spanel.add(Upanel); Upanel.setSize(new Dimension(800, 600)); Spanel.setSize(new Dimension(800, 600)); JFrame aWindow; aWindow = new JFrame("MVC-"); aWindow.getContentPane().add(Spanel); aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); aWindow.setSize(800, 600); aWindow.setVisible(true); Spanel.start(); Upanel.start(); } } import java.awt.*; import javax.swing.*; public class TestViewS extends JPanel implements Runnable{ static Thread thread; private static int interval_time = 5; int a = 100; int b = 100; public TestViewS(){ setBackground(Color.WHITE); } public void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(Color.BLUE); g.fillRect(a, b, 10, 10); } void start() { thread = new Thread(this); thread.start(); } public void run() { boolean checkA = true; boolean checkB = true; Thread thisThread = Thread.currentThread(); while (thisThread == thread) { try { if(checkA && checkB){ a++;} else if(!checkA && checkB){ b++;} else if(!checkA && !checkB){ a--;} else if(checkA && !checkB){ b--;} if(a == 701){ checkA = !checkA; a--;} else if(a == 99){ checkA = !checkA; a++;} if(b == 501){ checkB = !checkB; b--;} else if(b == 99){ checkB = !checkB; b++;} repaint(); Thread.sleep(interval_time); } catch (InterruptedException ie) { thread = null; break;}} } } import java.awt.*; import javax.swing.*; public class TestViewU extends JPanel implements Runnable{ static Thread thread; private static int interval_time = 5; int a = 200; int b = 200; public TestViewU(){ } public void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(Color.RED); g.fillRect(a, b, 10, 10); } void start() { thread = new Thread(this); thread.start(); } public void run() { boolean checkA = true; boolean checkB = true; Thread thisThread = Thread.currentThread(); while (thisThread == thread) { try { if(checkA && checkB){ a++;} else if(!checkA && checkB){ b++;} else if(!checkA && !checkB){ a--;} else if(checkA && !checkB){ b--;} if(a == 601){ checkA = !checkA; a--;} else if(a == 199){ checkA = !checkA; a++;} if(b == 401){ checkB = !checkB; b--;} else if(b == 199){ checkB = !checkB; b++;} repaint(a, b, 10, 10); Thread.sleep(interval_time); } catch (InterruptedException ie) { thread = null; break;}} } }